1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/spinctrl.cpp
3 // Purpose: wxSpinCtrl class implementation for Win32
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999-2005 Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
29 #include "wx/spinctrl.h"
32 #include "wx/hashmap.h"
33 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
35 #include "wx/textctrl.h"
36 #include "wx/wxcrtvararg.h"
39 #include "wx/msw/private.h"
42 #include "wx/tooltip.h"
43 #endif // wxUSE_TOOLTIPS
45 #include <limits.h> // for INT_MIN
47 // ----------------------------------------------------------------------------
49 // ----------------------------------------------------------------------------
51 BEGIN_EVENT_TABLE(wxSpinCtrl
, wxSpinButton
)
52 EVT_CHAR(wxSpinCtrl::OnChar
)
53 EVT_SET_FOCUS(wxSpinCtrl::OnSetFocus
)
54 EVT_KILL_FOCUS(wxSpinCtrl::OnKillFocus
)
57 #define GetBuddyHwnd() (HWND)(m_hwndBuddy)
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 // the margin between the up-down control and its buddy (can be arbitrary,
64 // choose what you like - or may be decide during run-time depending on the
66 static const int MARGIN_BETWEEN
= 1;
69 // ---------------------------------------------------------------------------
71 // ---------------------------------------------------------------------------
76 // Global hash used to find the spin control corresponding to the given buddy
78 WX_DECLARE_HASH_MAP(HWND
, wxSpinCtrl
*,
79 wxPointerHash
, wxPointerEqual
,
82 SpinForTextCtrl gs_spinForTextCtrl
;
84 } // anonymous namespace
86 // ============================================================================
88 // ============================================================================
90 // ----------------------------------------------------------------------------
91 // wnd proc for the buddy text ctrl
92 // ----------------------------------------------------------------------------
94 LRESULT APIENTRY _EXPORT
wxBuddyTextWndProc(HWND hwnd
,
99 wxSpinCtrl
* const spin
= wxSpinCtrl::GetSpinForTextCtrl(hwnd
);
101 // forward some messages (mostly the key and focus ones) to the spin ctrl
105 // if the focus comes from the spin control itself, don't set it
106 // back to it -- we don't want to go into an infinite loop
107 if ( (WXHWND
)wParam
== spin
->GetHWND() )
117 // we need to forward WM_HELP too to ensure that the context help
118 // associated with wxSpinCtrl is shown when the text control part of it
119 // is clicked with the "?" cursor
124 if ( spin
->MSWHandleMessage(&result
, message
, wParam
, lParam
) )
126 // Do not let the message be processed by the window proc
127 // of the text control if it had been already handled at wx
128 // level, this is consistent with what happens for normal,
129 // non-composite controls.
133 // The control may have been deleted at this point, so check.
134 if ( !::IsWindow(hwnd
) )
140 if ( spin
->HasFlag(wxTE_PROCESS_ENTER
) )
142 long dlgCode
= ::CallWindowProc
144 CASTWNDPROC spin
->GetBuddyWndProc(),
150 dlgCode
|= DLGC_WANTMESSAGE
;
156 return ::CallWindowProc(CASTWNDPROC spin
->GetBuddyWndProc(),
157 hwnd
, message
, wParam
, lParam
);
161 wxSpinCtrl
*wxSpinCtrl::GetSpinForTextCtrl(WXHWND hwndBuddy
)
163 const SpinForTextCtrl::const_iterator
164 it
= gs_spinForTextCtrl
.find(hwndBuddy
);
165 if ( it
== gs_spinForTextCtrl
.end() )
168 wxSpinCtrl
* const spin
= it
->second
;
171 wxASSERT_MSG( spin
->m_hwndBuddy
== hwndBuddy
,
172 wxT("wxSpinCtrl has incorrect buddy HWND!") );
177 // process a WM_COMMAND generated by the buddy text control
178 bool wxSpinCtrl::ProcessTextCommand(WXWORD cmd
, WXWORD
WXUNUSED(id
))
180 if ( (cmd
== EN_CHANGE
) && (!m_blockEvent
))
182 wxCommandEvent
event(wxEVT_TEXT
, GetId());
183 event
.SetEventObject(this);
184 wxString val
= wxGetWindowText(m_hwndBuddy
);
185 event
.SetString(val
);
186 event
.SetInt(GetValue());
187 return HandleWindowEvent(event
);
194 void wxSpinCtrl::OnChar(wxKeyEvent
& event
)
196 switch ( event
.GetKeyCode() )
200 wxCommandEvent
event(wxEVT_TEXT_ENTER
, m_windowId
);
201 InitCommandEvent(event
);
202 wxString val
= wxGetWindowText(m_hwndBuddy
);
203 event
.SetString(val
);
204 event
.SetInt(GetValue());
205 if ( HandleWindowEvent(event
) )
211 // always produce navigation event - even if we process TAB
212 // ourselves the fact that we got here means that the user code
213 // decided to skip processing of this TAB - probably to let it
214 // do its default job.
216 wxNavigationKeyEvent eventNav
;
217 eventNav
.SetDirection(!event
.ShiftDown());
218 eventNav
.SetWindowChange(event
.ControlDown());
219 eventNav
.SetEventObject(this);
221 if ( GetParent()->HandleWindowEvent(eventNav
) )
227 // no, we didn't process it
231 void wxSpinCtrl::OnKillFocus(wxFocusEvent
& event
)
233 // ensure that a correct value is shown by the control
238 void wxSpinCtrl::OnSetFocus(wxFocusEvent
& event
)
240 // when we get focus, give it to our buddy window as it needs it more than
242 ::SetFocus((HWND
)m_hwndBuddy
);
247 void wxSpinCtrl::NormalizeValue()
249 const int value
= GetValue();
250 const bool changed
= value
!= m_oldValue
;
252 // notice that we have to call SetValue() even if the value didn't change
253 // because otherwise we could be left with empty buddy control when value
254 // is 0, see comment in SetValue()
259 SendSpinUpdate(value
);
263 // ----------------------------------------------------------------------------
265 // ----------------------------------------------------------------------------
267 void wxSpinCtrl::Init()
269 m_blockEvent
= false;
271 m_wndProcBuddy
= NULL
;
272 m_oldValue
= INT_MIN
;
275 bool wxSpinCtrl::Create(wxWindow
*parent
,
277 const wxString
& value
,
281 int min
, int max
, int initial
,
282 const wxString
& name
)
284 // before using DoGetBestSize(), have to set style to let the base class
285 // know whether this is a horizontal or vertical control (we're always
287 style
|= wxSP_VERTICAL
;
289 if ( (style
& wxBORDER_MASK
) == wxBORDER_DEFAULT
)
291 style
|= wxBORDER_SIMPLE
;
293 style
|= wxBORDER_SUNKEN
;
296 SetWindowStyle(style
);
299 WXDWORD msStyle
= MSWGetStyle(GetWindowStyle(), & exStyle
) ;
301 // Scroll text automatically if there is not enough space to show all of
302 // it, this is better than not allowing to enter more digits at all.
303 msStyle
|= ES_AUTOHSCROLL
;
305 // propagate text alignment style to text ctrl
306 if ( style
& wxALIGN_RIGHT
)
308 else if ( style
& wxALIGN_CENTER
)
309 msStyle
|= ES_CENTER
;
311 // calculate the sizes: the size given is the total size for both controls
312 // and we need to fit them both in the given width (height is the same)
313 wxSize
sizeText(size
), sizeBtn(size
);
314 sizeBtn
.x
= wxSpinButton::DoGetBestSize().x
;
315 if ( sizeText
.x
<= 0 )
317 // DEFAULT_ITEM_WIDTH is the default width for the text control
318 sizeText
.x
= DEFAULT_ITEM_WIDTH
+ MARGIN_BETWEEN
+ sizeBtn
.x
;
321 sizeText
.x
-= sizeBtn
.x
+ MARGIN_BETWEEN
;
322 if ( sizeText
.x
<= 0 )
324 wxLogDebug(wxS("wxSpinCtrl \"%s\": initial width %d is too small, ")
325 wxS("at least %d pixels needed."),
326 name
, size
.x
, sizeBtn
.x
+ MARGIN_BETWEEN
+ 1);
330 posBtn
.x
+= sizeText
.x
+ MARGIN_BETWEEN
;
332 // we must create the text control before the spin button for the purpose
333 // of the dialog navigation: if there is a static text just before the spin
334 // control, activating it by Alt-letter should give focus to the text
335 // control, not the spin and the dialog navigation code will give focus to
336 // the next control (at Windows level), not the one after it
338 // create the text window
340 m_hwndBuddy
= (WXHWND
)::CreateWindowEx
342 exStyle
, // sunken border
343 wxT("EDIT"), // window class
344 NULL
, // no window title
345 msStyle
, // style (will be shown later)
346 pos
.x
, pos
.y
, // position
347 0, 0, // size (will be set later)
348 GetHwndOf(parent
), // parent
349 (HMENU
)-1, // control id
350 wxGetInstance(), // app instance
351 NULL
// unused client data
356 wxLogLastError(wxT("CreateWindow(buddy text window)"));
362 // create the spin button
363 if ( !wxSpinButton::Create(parent
, id
, posBtn
, sizeBtn
, style
, name
) )
368 wxSpinButtonBase::SetRange(min
, max
);
370 // subclass the text ctrl to be able to intercept some events
371 gs_spinForTextCtrl
[GetBuddyHwnd()] = this;
373 m_wndProcBuddy
= (WXFARPROC
)wxSetWindowProc(GetBuddyHwnd(),
376 // set up fonts and colours (This is nomally done in MSWCreateControl)
379 SetFont(GetDefaultAttributes().font
);
381 // set the size of the text window - can do it only now, because we
382 // couldn't call DoGetBestSize() before as font wasn't set
383 if ( sizeText
.y
<= 0 )
386 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
388 sizeText
.y
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
);
391 SetInitialSize(size
);
393 (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW
);
395 // associate the text window with the spin button
396 (void)::SendMessage(GetHwnd(), UDM_SETBUDDY
, (WPARAM
)m_hwndBuddy
, 0);
398 // If the initial text value is actually a number, it overrides the
399 // "initial" argument specified later.
400 long initialFromText
;
401 if ( value
.ToLong(&initialFromText
) )
402 initial
= initialFromText
;
404 // Set the range in the native control: notice that we must do it before
405 // calling SetValue() to use the correct validity checks for the initial
410 // Also set the text part of the control if it was specified independently
411 // but don't generate an event for this, it would be unexpected.
413 if ( !value
.empty() )
415 m_blockEvent
= false;
420 wxSpinCtrl::~wxSpinCtrl()
422 // destroy the buddy window because this pointer which wxBuddyTextWndProc
423 // uses will not soon be valid any more
424 ::DestroyWindow( GetBuddyHwnd() );
426 gs_spinForTextCtrl
.erase(GetBuddyHwnd());
429 // ----------------------------------------------------------------------------
430 // wxSpinCtrl-specific methods
431 // ----------------------------------------------------------------------------
433 int wxSpinCtrl::GetBase() const
435 return ::SendMessage(GetHwnd(), UDM_GETBASE
, 0, 0);
438 bool wxSpinCtrl::SetBase(int base
)
440 if ( !::SendMessage(GetHwnd(), UDM_SETBASE
, base
, 0) )
443 // Whether we need to be able enter "x" or not influences whether we should
444 // use ES_NUMBER for the buddy control.
450 // ----------------------------------------------------------------------------
451 // wxTextCtrl-like methods
452 // ----------------------------------------------------------------------------
454 void wxSpinCtrl::SetValue(const wxString
& text
)
456 if ( !::SetWindowText(GetBuddyHwnd(), text
.c_str()) )
458 wxLogLastError(wxT("SetWindowText(buddy)"));
462 void wxSpinCtrl::SetValue(int val
)
466 wxSpinButton::SetValue(val
);
468 // Normally setting the value of the spin button is enough as it updates
469 // its buddy control automatically but in a couple of situations it doesn't
470 // do it, for whatever reason, do it explicitly then:
471 const wxString text
= wxGetWindowText(m_hwndBuddy
);
473 // First case is when the text control is empty and the value is 0: the
474 // spin button just leaves it empty in this case, while we want to show 0
476 if ( text
.empty() && !val
)
478 ::SetWindowText(GetBuddyHwnd(), wxT("0"));
481 // Another one is when we're using hexadecimal base but the user input
482 // doesn't start with "0x" -- we prefer to show it to avoid ambiguity
483 // between decimal and hexadecimal.
484 if ( GetBase() == 16 &&
485 (text
.length() < 3 || text
[0] != '0' ||
486 (text
[1] != 'x' && text
[1] != 'X')) )
488 ::SetWindowText(GetBuddyHwnd(),
489 wxPrivate::wxSpinCtrlFormatAsHex(val
, m_max
).t_str());
492 m_oldValue
= GetValue();
494 m_blockEvent
= false;
497 int wxSpinCtrl::GetValue() const
499 const wxString val
= wxGetWindowText(m_hwndBuddy
);
502 if ( !val
.ToLong(&n
, GetBase()) )
513 void wxSpinCtrl::SetSelection(long from
, long to
)
515 // if from and to are both -1, it means (in wxWidgets) that all text should
516 // be selected - translate into Windows convention
517 if ( (from
== -1) && (to
== -1) )
522 ::SendMessage(GetBuddyHwnd(), EM_SETSEL
, (WPARAM
)from
, (LPARAM
)to
);
525 // ----------------------------------------------------------------------------
526 // wxSpinButton methods
527 // ----------------------------------------------------------------------------
529 void wxSpinCtrl::SetRange(int minVal
, int maxVal
)
531 // Manually adjust the old value to avoid an event being sent from
532 // NormalizeValue() called from inside the base class SetRange() as we're
533 // not supposed to generate any events from here.
534 if ( m_oldValue
< minVal
)
536 else if ( m_oldValue
> maxVal
)
539 wxSpinButton::SetRange(minVal
, maxVal
);
544 void wxSpinCtrl::UpdateBuddyStyle()
546 // this control is used for numeric entry so restrict the input to numeric
547 // keys only -- but only if we don't need to be able to enter "-" in it as
548 // otherwise this would become impossible and also if we don't use
549 // hexadecimal as entering "x" of the "0x" prefix wouldn't be allowed
551 const DWORD styleOld
= ::GetWindowLong(GetBuddyHwnd(), GWL_STYLE
);
553 if ( m_min
< 0 || GetBase() != 10 )
554 styleNew
= styleOld
& ~ES_NUMBER
;
556 styleNew
= styleOld
| ES_NUMBER
;
558 if ( styleNew
!= styleOld
)
559 ::SetWindowLong(GetBuddyHwnd(), GWL_STYLE
, styleNew
);
562 // ----------------------------------------------------------------------------
563 // forward some methods to subcontrols
564 // ----------------------------------------------------------------------------
566 bool wxSpinCtrl::SetFont(const wxFont
& font
)
568 if ( !wxWindowBase::SetFont(font
) )
574 WXHANDLE hFont
= GetFont().GetResourceHandle();
575 (void)::SendMessage(GetBuddyHwnd(), WM_SETFONT
, (WPARAM
)hFont
, TRUE
);
580 bool wxSpinCtrl::Show(bool show
)
582 if ( !wxControl::Show(show
) )
587 ::ShowWindow(GetBuddyHwnd(), show
? SW_SHOW
: SW_HIDE
);
592 bool wxSpinCtrl::Reparent(wxWindowBase
*newParent
)
594 // Reparenting both the updown control and its buddy does not seem to work:
595 // they continue to be connected somehow, but visually there is no feedback
596 // on the buddy edit control. To avoid this problem, we reparent the buddy
597 // window normally, but we recreate the updown control and reassign its
600 // Get the position before changing the parent as it would be offset after
602 const wxRect rect
= GetRect();
604 if ( !wxWindowBase::Reparent(newParent
) )
607 newParent
->GetChildren().DeleteObject(this);
609 // destroy the old spin button after detaching it from this wxWindow object
610 // (notice that m_hWnd will be reset by UnsubclassWin() so save it first)
611 const HWND hwndOld
= GetHwnd();
613 if ( !::DestroyWindow(hwndOld
) )
615 wxLogLastError(wxT("DestroyWindow"));
618 // create and initialize the new one
619 if ( !wxSpinButton::Create(GetParent(), GetId(),
620 rect
.GetPosition(), rect
.GetSize(),
621 GetWindowStyle(), GetName()) )
624 // reapply our values to wxSpinButton
625 wxSpinButton::SetValue(GetValue());
626 SetRange(m_min
, m_max
);
628 // also set the size again with wxSIZE_ALLOW_MINUS_ONE flag: this is
629 // necessary if our original position used -1 for either x or y
630 SetSize(rect
, wxSIZE_ALLOW_MINUS_ONE
);
632 // associate it with the buddy control again
633 ::SetParent(GetBuddyHwnd(), GetHwndOf(GetParent()));
634 (void)::SendMessage(GetHwnd(), UDM_SETBUDDY
, (WPARAM
)GetBuddyHwnd(), 0);
639 bool wxSpinCtrl::Enable(bool enable
)
641 if ( !wxControl::Enable(enable
) )
646 MSWEnableHWND(GetBuddyHwnd(), enable
);
651 void wxSpinCtrl::SetFocus()
653 ::SetFocus(GetBuddyHwnd());
658 void wxSpinCtrl::DoSetToolTip(wxToolTip
*tip
)
660 wxSpinButton::DoSetToolTip(tip
);
663 tip
->AddOtherWindow(m_hwndBuddy
);
666 #endif // wxUSE_TOOLTIPS
668 // ----------------------------------------------------------------------------
669 // events processing and generation
670 // ----------------------------------------------------------------------------
672 void wxSpinCtrl::SendSpinUpdate(int value
)
674 wxCommandEvent
event(wxEVT_SPINCTRL
, GetId());
675 event
.SetEventObject(this);
678 (void)HandleWindowEvent(event
);
683 bool wxSpinCtrl::MSWOnScroll(int WXUNUSED(orientation
), WXWORD wParam
,
684 WXWORD
WXUNUSED(pos
), WXHWND control
)
686 wxCHECK_MSG( control
, false, wxT("scrolling what?") );
688 if ( wParam
!= SB_THUMBPOSITION
)
690 // probable SB_ENDSCROLL - we don't react to it
694 // Notice that we can't use "pos" from WM_VSCROLL as it is 16 bit and we
695 // might be using 32 bit range.
696 int new_value
= GetValue();
697 if (m_oldValue
!= new_value
)
698 SendSpinUpdate( new_value
);
703 bool wxSpinCtrl::MSWOnNotify(int WXUNUSED(idCtrl
), WXLPARAM lParam
, WXLPARAM
*result
)
705 NM_UPDOWN
*lpnmud
= (NM_UPDOWN
*)lParam
;
707 if (lpnmud
->hdr
.hwndFrom
!= GetHwnd()) // make sure it is the right control
710 *result
= 0; // never reject UP and DOWN events
716 // ----------------------------------------------------------------------------
718 // ----------------------------------------------------------------------------
720 wxSize
wxSpinCtrl::DoGetBestSize() const
722 return DoGetSizeFromTextSize(DEFAULT_ITEM_WIDTH
);
725 wxSize
wxSpinCtrl::DoGetSizeFromTextSize(int xlen
, int ylen
) const
727 wxSize sizeBtn
= wxSpinButton::DoGetBestSize();
730 wxGetCharSize(GetHWND(), NULL
, &y
, GetFont());
731 // JACS: we should always use the height calculated
732 // from above, because otherwise we'll get a spin control
733 // that's too big. So never use the height calculated
734 // from wxSpinButton::DoGetBestSize().
736 wxSize
tsize(xlen
+ sizeBtn
.x
+ MARGIN_BETWEEN
+ 3*y
/10 + 10,
737 EDIT_HEIGHT_FROM_CHAR_HEIGHT(y
));
739 // Check if the user requested a non-standard height.
741 tsize
.IncBy(0, ylen
- y
);
746 void wxSpinCtrl::DoMoveWindow(int x
, int y
, int width
, int height
)
748 int widthBtn
= wxSpinButton::DoGetBestSize().x
;
749 int widthText
= width
- widthBtn
- MARGIN_BETWEEN
;
752 // This can happen during the initial window layout when it's total
753 // size is too small to accommodate all the controls and usually is not
754 // a problem because the window will be relaid out with enough space
755 // later. Of course, if it isn't and this is our final size, then we
756 // have a real problem but as we don't know if this is going to be the
757 // case or not, just hope for the best -- we used to give a debug
758 // warning here and this was annoying as it could result in dozens of
759 // perfectly harmless warnings.
763 // 1) The buddy window
764 DoMoveSibling(m_hwndBuddy
, x
, y
, widthText
, height
);
766 // 2) The button window
768 x
+= widthText
+ MARGIN_BETWEEN
;
769 wxSpinButton::DoMoveWindow(x
, y
, widthBtn
, height
);
772 // get total size of the control
773 void wxSpinCtrl::DoGetSize(int *x
, int *y
) const
775 RECT spinrect
, textrect
, ctrlrect
;
776 GetWindowRect(GetHwnd(), &spinrect
);
777 GetWindowRect(GetBuddyHwnd(), &textrect
);
778 UnionRect(&ctrlrect
,&textrect
, &spinrect
);
781 *x
= ctrlrect
.right
- ctrlrect
.left
;
783 *y
= ctrlrect
.bottom
- ctrlrect
.top
;
786 void wxSpinCtrl::DoGetClientSize(int *x
, int *y
) const
788 RECT spinrect
= wxGetClientRect(GetHwnd());
789 RECT textrect
= wxGetClientRect(GetBuddyHwnd());
791 UnionRect(&ctrlrect
,&textrect
, &spinrect
);
794 *x
= ctrlrect
.right
- ctrlrect
.left
;
796 *y
= ctrlrect
.bottom
- ctrlrect
.top
;
799 void wxSpinCtrl::DoGetPosition(int *x
, int *y
) const
801 // hack: pretend that our HWND is the text control just for a moment
802 WXHWND hWnd
= GetHWND();
803 wxConstCast(this, wxSpinCtrl
)->m_hWnd
= m_hwndBuddy
;
805 wxSpinButton::DoGetPosition(x
, y
);
807 wxConstCast(this, wxSpinCtrl
)->m_hWnd
= hWnd
;
810 #endif // wxUSE_SPINCTRL