1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/spinctrl.cpp
3 // Purpose: wxSpinCtrl class implementation for Win32
4 // Author: Vadim Zeitlin
7 // Copyright: (c) 1999-2005 Vadim Zeitlin
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
28 #include "wx/spinctrl.h"
31 #include "wx/hashmap.h"
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
34 #include "wx/textctrl.h"
35 #include "wx/wxcrtvararg.h"
38 #include "wx/msw/private.h"
41 #include "wx/tooltip.h"
42 #endif // wxUSE_TOOLTIPS
44 #include <limits.h> // for INT_MIN
46 // ----------------------------------------------------------------------------
48 // ----------------------------------------------------------------------------
50 BEGIN_EVENT_TABLE(wxSpinCtrl
, wxSpinButton
)
51 EVT_CHAR(wxSpinCtrl::OnChar
)
52 EVT_SET_FOCUS(wxSpinCtrl::OnSetFocus
)
53 EVT_KILL_FOCUS(wxSpinCtrl::OnKillFocus
)
56 #define GetBuddyHwnd() (HWND)(m_hwndBuddy)
58 // ----------------------------------------------------------------------------
60 // ----------------------------------------------------------------------------
62 // the margin between the up-down control and its buddy (can be arbitrary,
63 // choose what you like - or may be decide during run-time depending on the
65 static const int MARGIN_BETWEEN
= 1;
68 // ---------------------------------------------------------------------------
70 // ---------------------------------------------------------------------------
75 // Global hash used to find the spin control corresponding to the given buddy
77 WX_DECLARE_HASH_MAP(HWND
, wxSpinCtrl
*,
78 wxPointerHash
, wxPointerEqual
,
81 SpinForTextCtrl gs_spinForTextCtrl
;
83 } // anonymous namespace
85 // ============================================================================
87 // ============================================================================
89 // ----------------------------------------------------------------------------
90 // wnd proc for the buddy text ctrl
91 // ----------------------------------------------------------------------------
93 LRESULT APIENTRY _EXPORT
wxBuddyTextWndProc(HWND hwnd
,
98 wxSpinCtrl
* const spin
= wxSpinCtrl::GetSpinForTextCtrl(hwnd
);
100 // forward some messages (mostly the key and focus ones) to the spin ctrl
104 // if the focus comes from the spin control itself, don't set it
105 // back to it -- we don't want to go into an infinite loop
106 if ( (WXHWND
)wParam
== spin
->GetHWND() )
116 // we need to forward WM_HELP too to ensure that the context help
117 // associated with wxSpinCtrl is shown when the text control part of it
118 // is clicked with the "?" cursor
123 if ( spin
->MSWHandleMessage(&result
, message
, wParam
, lParam
) )
125 // Do not let the message be processed by the window proc
126 // of the text control if it had been already handled at wx
127 // level, this is consistent with what happens for normal,
128 // non-composite controls.
132 // The control may have been deleted at this point, so check.
133 if ( !::IsWindow(hwnd
) )
139 if ( spin
->HasFlag(wxTE_PROCESS_ENTER
) )
141 long dlgCode
= ::CallWindowProc
143 CASTWNDPROC spin
->GetBuddyWndProc(),
149 dlgCode
|= DLGC_WANTMESSAGE
;
155 return ::CallWindowProc(CASTWNDPROC spin
->GetBuddyWndProc(),
156 hwnd
, message
, wParam
, lParam
);
160 wxSpinCtrl
*wxSpinCtrl::GetSpinForTextCtrl(WXHWND hwndBuddy
)
162 const SpinForTextCtrl::const_iterator
163 it
= gs_spinForTextCtrl
.find(hwndBuddy
);
164 if ( it
== gs_spinForTextCtrl
.end() )
167 wxSpinCtrl
* const spin
= it
->second
;
170 wxASSERT_MSG( spin
->m_hwndBuddy
== hwndBuddy
,
171 wxT("wxSpinCtrl has incorrect buddy HWND!") );
176 // process a WM_COMMAND generated by the buddy text control
177 bool wxSpinCtrl::ProcessTextCommand(WXWORD cmd
, WXWORD
WXUNUSED(id
))
179 if ( (cmd
== EN_CHANGE
) && (!m_blockEvent
))
181 wxCommandEvent
event(wxEVT_TEXT
, GetId());
182 event
.SetEventObject(this);
183 wxString val
= wxGetWindowText(m_hwndBuddy
);
184 event
.SetString(val
);
185 event
.SetInt(GetValue());
186 return HandleWindowEvent(event
);
193 void wxSpinCtrl::OnChar(wxKeyEvent
& event
)
195 switch ( event
.GetKeyCode() )
199 wxCommandEvent
event(wxEVT_TEXT_ENTER
, m_windowId
);
200 InitCommandEvent(event
);
201 wxString val
= wxGetWindowText(m_hwndBuddy
);
202 event
.SetString(val
);
203 event
.SetInt(GetValue());
204 if ( HandleWindowEvent(event
) )
210 // always produce navigation event - even if we process TAB
211 // ourselves the fact that we got here means that the user code
212 // decided to skip processing of this TAB - probably to let it
213 // do its default job.
215 wxNavigationKeyEvent eventNav
;
216 eventNav
.SetDirection(!event
.ShiftDown());
217 eventNav
.SetWindowChange(event
.ControlDown());
218 eventNav
.SetEventObject(this);
220 if ( GetParent()->HandleWindowEvent(eventNav
) )
226 // no, we didn't process it
230 void wxSpinCtrl::OnKillFocus(wxFocusEvent
& event
)
232 // ensure that a correct value is shown by the control
237 void wxSpinCtrl::OnSetFocus(wxFocusEvent
& event
)
239 // when we get focus, give it to our buddy window as it needs it more than
241 ::SetFocus((HWND
)m_hwndBuddy
);
246 void wxSpinCtrl::NormalizeValue()
248 const int value
= GetValue();
249 const bool changed
= value
!= m_oldValue
;
251 // notice that we have to call SetValue() even if the value didn't change
252 // because otherwise we could be left with empty buddy control when value
253 // is 0, see comment in SetValue()
258 SendSpinUpdate(value
);
262 // ----------------------------------------------------------------------------
264 // ----------------------------------------------------------------------------
266 void wxSpinCtrl::Init()
268 m_blockEvent
= false;
270 m_wndProcBuddy
= NULL
;
271 m_oldValue
= INT_MIN
;
274 bool wxSpinCtrl::Create(wxWindow
*parent
,
276 const wxString
& value
,
280 int min
, int max
, int initial
,
281 const wxString
& name
)
283 // before using DoGetBestSize(), have to set style to let the base class
284 // know whether this is a horizontal or vertical control (we're always
286 style
|= wxSP_VERTICAL
;
288 if ( (style
& wxBORDER_MASK
) == wxBORDER_DEFAULT
)
290 style
|= wxBORDER_SIMPLE
;
292 style
|= wxBORDER_SUNKEN
;
295 SetWindowStyle(style
);
298 WXDWORD msStyle
= MSWGetStyle(GetWindowStyle(), & exStyle
) ;
300 // Scroll text automatically if there is not enough space to show all of
301 // it, this is better than not allowing to enter more digits at all.
302 msStyle
|= ES_AUTOHSCROLL
;
304 // propagate text alignment style to text ctrl
305 if ( style
& wxALIGN_RIGHT
)
307 else if ( style
& wxALIGN_CENTER
)
308 msStyle
|= ES_CENTER
;
310 // calculate the sizes: the size given is the total size for both controls
311 // and we need to fit them both in the given width (height is the same)
312 wxSize
sizeText(size
), sizeBtn(size
);
313 sizeBtn
.x
= wxSpinButton::DoGetBestSize().x
;
314 if ( sizeText
.x
<= 0 )
316 // DEFAULT_ITEM_WIDTH is the default width for the text control
317 sizeText
.x
= DEFAULT_ITEM_WIDTH
+ MARGIN_BETWEEN
+ sizeBtn
.x
;
320 sizeText
.x
-= sizeBtn
.x
+ MARGIN_BETWEEN
;
321 if ( sizeText
.x
<= 0 )
323 wxLogDebug(wxS("wxSpinCtrl \"%s\": initial width %d is too small, ")
324 wxS("at least %d pixels needed."),
325 name
, size
.x
, sizeBtn
.x
+ MARGIN_BETWEEN
+ 1);
329 posBtn
.x
+= sizeText
.x
+ MARGIN_BETWEEN
;
331 // we must create the text control before the spin button for the purpose
332 // of the dialog navigation: if there is a static text just before the spin
333 // control, activating it by Alt-letter should give focus to the text
334 // control, not the spin and the dialog navigation code will give focus to
335 // the next control (at Windows level), not the one after it
337 // create the text window
339 m_hwndBuddy
= (WXHWND
)::CreateWindowEx
341 exStyle
, // sunken border
342 wxT("EDIT"), // window class
343 NULL
, // no window title
344 msStyle
, // style (will be shown later)
345 pos
.x
, pos
.y
, // position
346 0, 0, // size (will be set later)
347 GetHwndOf(parent
), // parent
348 (HMENU
)-1, // control id
349 wxGetInstance(), // app instance
350 NULL
// unused client data
355 wxLogLastError(wxT("CreateWindow(buddy text window)"));
361 // create the spin button
362 if ( !wxSpinButton::Create(parent
, id
, posBtn
, sizeBtn
, style
, name
) )
367 wxSpinButtonBase::SetRange(min
, max
);
369 // subclass the text ctrl to be able to intercept some events
370 gs_spinForTextCtrl
[GetBuddyHwnd()] = this;
372 m_wndProcBuddy
= (WXFARPROC
)wxSetWindowProc(GetBuddyHwnd(),
375 // set up fonts and colours (This is nomally done in MSWCreateControl)
378 SetFont(GetDefaultAttributes().font
);
380 // set the size of the text window - can do it only now, because we
381 // couldn't call DoGetBestSize() before as font wasn't set
382 if ( sizeText
.y
<= 0 )
385 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
387 sizeText
.y
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
);
390 SetInitialSize(size
);
392 (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW
);
394 // associate the text window with the spin button
395 (void)::SendMessage(GetHwnd(), UDM_SETBUDDY
, (WPARAM
)m_hwndBuddy
, 0);
397 // If the initial text value is actually a number, it overrides the
398 // "initial" argument specified later.
399 long initialFromText
;
400 if ( value
.ToLong(&initialFromText
) )
401 initial
= initialFromText
;
403 // Set the range in the native control: notice that we must do it before
404 // calling SetValue() to use the correct validity checks for the initial
409 // Also set the text part of the control if it was specified independently
410 // but don't generate an event for this, it would be unexpected.
412 if ( !value
.empty() )
414 m_blockEvent
= false;
419 wxSpinCtrl::~wxSpinCtrl()
421 // destroy the buddy window because this pointer which wxBuddyTextWndProc
422 // uses will not soon be valid any more
423 ::DestroyWindow( GetBuddyHwnd() );
425 gs_spinForTextCtrl
.erase(GetBuddyHwnd());
428 // ----------------------------------------------------------------------------
429 // wxSpinCtrl-specific methods
430 // ----------------------------------------------------------------------------
432 int wxSpinCtrl::GetBase() const
434 return ::SendMessage(GetHwnd(), UDM_GETBASE
, 0, 0);
437 bool wxSpinCtrl::SetBase(int base
)
439 if ( !::SendMessage(GetHwnd(), UDM_SETBASE
, base
, 0) )
442 // Whether we need to be able enter "x" or not influences whether we should
443 // use ES_NUMBER for the buddy control.
449 // ----------------------------------------------------------------------------
450 // wxTextCtrl-like methods
451 // ----------------------------------------------------------------------------
453 void wxSpinCtrl::SetValue(const wxString
& text
)
455 if ( !::SetWindowText(GetBuddyHwnd(), text
.c_str()) )
457 wxLogLastError(wxT("SetWindowText(buddy)"));
461 void wxSpinCtrl::SetValue(int val
)
465 wxSpinButton::SetValue(val
);
467 // Normally setting the value of the spin button is enough as it updates
468 // its buddy control automatically but in a couple of situations it doesn't
469 // do it, for whatever reason, do it explicitly then:
470 const wxString text
= wxGetWindowText(m_hwndBuddy
);
472 // First case is when the text control is empty and the value is 0: the
473 // spin button just leaves it empty in this case, while we want to show 0
475 if ( text
.empty() && !val
)
477 ::SetWindowText(GetBuddyHwnd(), wxT("0"));
480 // Another one is when we're using hexadecimal base but the user input
481 // doesn't start with "0x" -- we prefer to show it to avoid ambiguity
482 // between decimal and hexadecimal.
483 if ( GetBase() == 16 &&
484 (text
.length() < 3 || text
[0] != '0' ||
485 (text
[1] != 'x' && text
[1] != 'X')) )
487 ::SetWindowText(GetBuddyHwnd(),
488 wxPrivate::wxSpinCtrlFormatAsHex(val
, m_max
).t_str());
491 m_oldValue
= GetValue();
493 m_blockEvent
= false;
496 int wxSpinCtrl::GetValue() const
498 const wxString val
= wxGetWindowText(m_hwndBuddy
);
501 if ( !val
.ToLong(&n
, GetBase()) )
512 void wxSpinCtrl::SetSelection(long from
, long to
)
514 // if from and to are both -1, it means (in wxWidgets) that all text should
515 // be selected - translate into Windows convention
516 if ( (from
== -1) && (to
== -1) )
521 ::SendMessage(GetBuddyHwnd(), EM_SETSEL
, (WPARAM
)from
, (LPARAM
)to
);
524 // ----------------------------------------------------------------------------
525 // wxSpinButton methods
526 // ----------------------------------------------------------------------------
528 void wxSpinCtrl::SetRange(int minVal
, int maxVal
)
530 // Manually adjust the old value to avoid an event being sent from
531 // NormalizeValue() called from inside the base class SetRange() as we're
532 // not supposed to generate any events from here.
533 if ( m_oldValue
< minVal
)
535 else if ( m_oldValue
> maxVal
)
538 wxSpinButton::SetRange(minVal
, maxVal
);
543 void wxSpinCtrl::UpdateBuddyStyle()
545 // this control is used for numeric entry so restrict the input to numeric
546 // keys only -- but only if we don't need to be able to enter "-" in it as
547 // otherwise this would become impossible and also if we don't use
548 // hexadecimal as entering "x" of the "0x" prefix wouldn't be allowed
550 const DWORD styleOld
= ::GetWindowLong(GetBuddyHwnd(), GWL_STYLE
);
552 if ( m_min
< 0 || GetBase() != 10 )
553 styleNew
= styleOld
& ~ES_NUMBER
;
555 styleNew
= styleOld
| ES_NUMBER
;
557 if ( styleNew
!= styleOld
)
558 ::SetWindowLong(GetBuddyHwnd(), GWL_STYLE
, styleNew
);
561 // ----------------------------------------------------------------------------
562 // forward some methods to subcontrols
563 // ----------------------------------------------------------------------------
565 bool wxSpinCtrl::SetFont(const wxFont
& font
)
567 if ( !wxWindowBase::SetFont(font
) )
573 WXHANDLE hFont
= GetFont().GetResourceHandle();
574 (void)::SendMessage(GetBuddyHwnd(), WM_SETFONT
, (WPARAM
)hFont
, TRUE
);
579 bool wxSpinCtrl::Show(bool show
)
581 if ( !wxControl::Show(show
) )
586 ::ShowWindow(GetBuddyHwnd(), show
? SW_SHOW
: SW_HIDE
);
591 bool wxSpinCtrl::Reparent(wxWindowBase
*newParent
)
593 // Reparenting both the updown control and its buddy does not seem to work:
594 // they continue to be connected somehow, but visually there is no feedback
595 // on the buddy edit control. To avoid this problem, we reparent the buddy
596 // window normally, but we recreate the updown control and reassign its
599 // Get the position before changing the parent as it would be offset after
601 const wxRect rect
= GetRect();
603 if ( !wxWindowBase::Reparent(newParent
) )
606 newParent
->GetChildren().DeleteObject(this);
608 // destroy the old spin button after detaching it from this wxWindow object
609 // (notice that m_hWnd will be reset by UnsubclassWin() so save it first)
610 const HWND hwndOld
= GetHwnd();
612 if ( !::DestroyWindow(hwndOld
) )
614 wxLogLastError(wxT("DestroyWindow"));
617 // create and initialize the new one
618 if ( !wxSpinButton::Create(GetParent(), GetId(),
619 rect
.GetPosition(), rect
.GetSize(),
620 GetWindowStyle(), GetName()) )
623 // reapply our values to wxSpinButton
624 wxSpinButton::SetValue(GetValue());
625 SetRange(m_min
, m_max
);
627 // also set the size again with wxSIZE_ALLOW_MINUS_ONE flag: this is
628 // necessary if our original position used -1 for either x or y
629 SetSize(rect
, wxSIZE_ALLOW_MINUS_ONE
);
631 // associate it with the buddy control again
632 ::SetParent(GetBuddyHwnd(), GetHwndOf(GetParent()));
633 (void)::SendMessage(GetHwnd(), UDM_SETBUDDY
, (WPARAM
)GetBuddyHwnd(), 0);
638 bool wxSpinCtrl::Enable(bool enable
)
640 if ( !wxControl::Enable(enable
) )
645 MSWEnableHWND(GetBuddyHwnd(), enable
);
650 void wxSpinCtrl::SetFocus()
652 ::SetFocus(GetBuddyHwnd());
657 void wxSpinCtrl::DoSetToolTip(wxToolTip
*tip
)
659 wxSpinButton::DoSetToolTip(tip
);
662 tip
->AddOtherWindow(m_hwndBuddy
);
665 #endif // wxUSE_TOOLTIPS
667 // ----------------------------------------------------------------------------
668 // events processing and generation
669 // ----------------------------------------------------------------------------
671 void wxSpinCtrl::SendSpinUpdate(int value
)
673 wxCommandEvent
event(wxEVT_SPINCTRL
, GetId());
674 event
.SetEventObject(this);
677 (void)HandleWindowEvent(event
);
682 bool wxSpinCtrl::MSWOnScroll(int WXUNUSED(orientation
), WXWORD wParam
,
683 WXWORD
WXUNUSED(pos
), WXHWND control
)
685 wxCHECK_MSG( control
, false, wxT("scrolling what?") );
687 if ( wParam
!= SB_THUMBPOSITION
)
689 // probable SB_ENDSCROLL - we don't react to it
693 // Notice that we can't use "pos" from WM_VSCROLL as it is 16 bit and we
694 // might be using 32 bit range.
695 int new_value
= GetValue();
696 if (m_oldValue
!= new_value
)
697 SendSpinUpdate( new_value
);
702 bool wxSpinCtrl::MSWOnNotify(int WXUNUSED(idCtrl
), WXLPARAM lParam
, WXLPARAM
*result
)
704 NM_UPDOWN
*lpnmud
= (NM_UPDOWN
*)lParam
;
706 if (lpnmud
->hdr
.hwndFrom
!= GetHwnd()) // make sure it is the right control
709 *result
= 0; // never reject UP and DOWN events
715 // ----------------------------------------------------------------------------
717 // ----------------------------------------------------------------------------
719 wxSize
wxSpinCtrl::DoGetBestSize() const
721 return DoGetSizeFromTextSize(DEFAULT_ITEM_WIDTH
);
724 wxSize
wxSpinCtrl::DoGetSizeFromTextSize(int xlen
, int ylen
) const
726 wxSize sizeBtn
= wxSpinButton::DoGetBestSize();
729 wxGetCharSize(GetHWND(), NULL
, &y
, GetFont());
730 // JACS: we should always use the height calculated
731 // from above, because otherwise we'll get a spin control
732 // that's too big. So never use the height calculated
733 // from wxSpinButton::DoGetBestSize().
735 wxSize
tsize(xlen
+ sizeBtn
.x
+ MARGIN_BETWEEN
+ 3*y
/10 + 10,
736 EDIT_HEIGHT_FROM_CHAR_HEIGHT(y
));
738 // Check if the user requested a non-standard height.
740 tsize
.IncBy(0, ylen
- y
);
745 void wxSpinCtrl::DoMoveWindow(int x
, int y
, int width
, int height
)
747 int widthBtn
= wxSpinButton::DoGetBestSize().x
;
748 int widthText
= width
- widthBtn
- MARGIN_BETWEEN
;
751 // This can happen during the initial window layout when it's total
752 // size is too small to accommodate all the controls and usually is not
753 // a problem because the window will be relaid out with enough space
754 // later. Of course, if it isn't and this is our final size, then we
755 // have a real problem but as we don't know if this is going to be the
756 // case or not, just hope for the best -- we used to give a debug
757 // warning here and this was annoying as it could result in dozens of
758 // perfectly harmless warnings.
762 // 1) The buddy window
763 DoMoveSibling(m_hwndBuddy
, x
, y
, widthText
, height
);
765 // 2) The button window
767 x
+= widthText
+ MARGIN_BETWEEN
;
768 wxSpinButton::DoMoveWindow(x
, y
, widthBtn
, height
);
771 // get total size of the control
772 void wxSpinCtrl::DoGetSize(int *x
, int *y
) const
774 RECT spinrect
, textrect
, ctrlrect
;
775 GetWindowRect(GetHwnd(), &spinrect
);
776 GetWindowRect(GetBuddyHwnd(), &textrect
);
777 UnionRect(&ctrlrect
,&textrect
, &spinrect
);
780 *x
= ctrlrect
.right
- ctrlrect
.left
;
782 *y
= ctrlrect
.bottom
- ctrlrect
.top
;
785 void wxSpinCtrl::DoGetClientSize(int *x
, int *y
) const
787 RECT spinrect
= wxGetClientRect(GetHwnd());
788 RECT textrect
= wxGetClientRect(GetBuddyHwnd());
790 UnionRect(&ctrlrect
,&textrect
, &spinrect
);
793 *x
= ctrlrect
.right
- ctrlrect
.left
;
795 *y
= ctrlrect
.bottom
- ctrlrect
.top
;
798 void wxSpinCtrl::DoGetPosition(int *x
, int *y
) const
800 // hack: pretend that our HWND is the text control just for a moment
801 WXHWND hWnd
= GetHWND();
802 wxConstCast(this, wxSpinCtrl
)->m_hWnd
= m_hwndBuddy
;
804 wxSpinButton::DoGetPosition(x
, y
);
806 wxConstCast(this, wxSpinCtrl
)->m_hWnd
= hWnd
;
809 #endif // wxUSE_SPINCTRL