1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/choice.cpp
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin to derive from wxChoiceBase
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_CHOICE && !(defined(__SMARTPHONE__) && defined(__WXWINCE__))
29 #include "wx/choice.h"
36 #include "wx/settings.h"
39 #include "wx/msw/private.h"
41 // ============================================================================
43 // ============================================================================
45 // ----------------------------------------------------------------------------
47 // ----------------------------------------------------------------------------
49 bool wxChoice::Create(wxWindow
*parent
,
53 int n
, const wxString choices
[],
55 const wxValidator
& validator
,
58 // Experience shows that wxChoice vs. wxComboBox distinction confuses
59 // quite a few people - try to help them
60 wxASSERT_MSG( !(style
& wxCB_DROPDOWN
) &&
61 !(style
& wxCB_READONLY
) &&
62 !(style
& wxCB_SIMPLE
),
63 wxT("this style flag is ignored by wxChoice, you ")
64 wxT("probably want to use a wxComboBox") );
66 return CreateAndInit(parent
, id
, pos
, size
, n
, choices
, style
,
70 bool wxChoice::CreateAndInit(wxWindow
*parent
,
74 int n
, const wxString choices
[],
76 const wxValidator
& validator
,
79 // initialize wxControl
80 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
83 // now create the real HWND
84 if ( !MSWCreateControl(wxT("COMBOBOX"), wxEmptyString
, pos
, size
) )
88 // initialize the controls contents
91 // and now we may finally size the control properly (if needed)
97 void wxChoice::SetLabel(const wxString
& label
)
99 if ( FindString(label
) == wxNOT_FOUND
)
101 // unless we explicitly do this here, CB_GETCURSEL will continue to
102 // return the index of the previously selected item which will result
103 // in wrongly replacing the value being set now with the previously
104 // value if the user simply opens and closes (without selecting
105 // anything) the combobox popup
109 wxChoiceBase::SetLabel(label
);
112 bool wxChoice::Create(wxWindow
*parent
,
116 const wxArrayString
& choices
,
118 const wxValidator
& validator
,
119 const wxString
& name
)
121 wxCArrayString
chs(choices
);
122 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
123 style
, validator
, name
);
126 bool wxChoice::MSWShouldPreProcessMessage(WXMSG
*pMsg
)
128 MSG
*msg
= (MSG
*) pMsg
;
130 // if the dropdown list is visible, don't preprocess certain keys
131 if ( msg
->message
== WM_KEYDOWN
132 && (msg
->wParam
== VK_ESCAPE
|| msg
->wParam
== VK_RETURN
) )
134 if (::SendMessage(GetHwndOf(this), CB_GETDROPPEDSTATE
, 0, 0))
140 return wxControl::MSWShouldPreProcessMessage(pMsg
);
143 WXDWORD
wxChoice::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
145 // we never have an external border
146 WXDWORD msStyle
= wxControl::MSWGetStyle
148 (style
& ~wxBORDER_MASK
) | wxBORDER_NONE
, exstyle
151 // WS_CLIPSIBLINGS is useful with wxChoice and doesn't seem to result in
153 msStyle
|= WS_CLIPSIBLINGS
;
155 // wxChoice-specific styles
156 msStyle
|= CBS_DROPDOWNLIST
| WS_HSCROLL
| WS_VSCROLL
;
157 if ( style
& wxCB_SORT
)
164 #define EP_EDITTEXT 1
169 wxChoice::GetClassDefaultAttributes(wxWindowVariant
WXUNUSED(variant
))
171 // it is important to return valid values for all attributes from here,
172 // GetXXX() below rely on this
173 wxVisualAttributes attrs
;
175 // FIXME: Use better dummy window?
176 wxWindow
* wnd
= wxTheApp
->GetTopWindow();
180 attrs
.font
= wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT
);
182 // there doesn't seem to be any way to get the text colour using themes
183 // API: TMT_TEXTCOLOR doesn't work neither for EDIT nor COMBOBOX
184 attrs
.colFg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
);
186 // NB: use EDIT, not COMBOBOX (the latter works in XP but not Vista)
187 attrs
.colBg
= wnd
->MSWGetThemeColour(L
"EDIT",
190 ThemeColourBackground
,
191 wxSYS_COLOUR_WINDOW
);
196 wxChoice::~wxChoice()
201 // ----------------------------------------------------------------------------
202 // adding/deleting items to/from the list
203 // ----------------------------------------------------------------------------
205 int wxChoice::DoInsertItems(const wxArrayStringsAdapter
& items
,
207 void **clientData
, wxClientDataType type
)
209 MSWAllocStorage(items
, CB_INITSTORAGE
);
211 const bool append
= pos
== GetCount();
213 // use CB_ADDSTRING when appending at the end to make sure the control is
214 // resorted if it has wxCB_SORT style
215 const unsigned msg
= append
? CB_ADDSTRING
: CB_INSERTSTRING
;
221 const unsigned numItems
= items
.GetCount();
222 for ( unsigned i
= 0; i
< numItems
; ++i
)
224 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
225 if ( n
== wxNOT_FOUND
)
231 AssignNewItemClientData(n
, clientData
, i
, type
);
234 // we need to refresh our size in order to have enough space for the
237 MSWUpdateDropDownHeight();
239 InvalidateBestSize();
244 void wxChoice::DoDeleteOneItem(unsigned int n
)
246 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::Delete") );
248 SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
251 MSWUpdateDropDownHeight();
253 InvalidateBestSize();
256 void wxChoice::DoClear()
258 SendMessage(GetHwnd(), CB_RESETCONTENT
, 0, 0);
261 MSWUpdateDropDownHeight();
263 InvalidateBestSize();
266 // ----------------------------------------------------------------------------
268 // ----------------------------------------------------------------------------
270 int wxChoice::GetSelection() const
272 // if m_lastAcceptedSelection is set, it means that the dropdown is
273 // currently shown and that we want to use the last "permanent" selection
274 // instead of whatever is under the mouse pointer currently
276 // otherwise, get the selection from the control
277 return m_lastAcceptedSelection
== wxID_NONE
? GetCurrentSelection()
278 : m_lastAcceptedSelection
;
281 int wxChoice::GetCurrentSelection() const
283 return (int)SendMessage(GetHwnd(), CB_GETCURSEL
, 0, 0);
286 void wxChoice::SetSelection(int n
)
288 SendMessage(GetHwnd(), CB_SETCURSEL
, n
, 0);
291 // ----------------------------------------------------------------------------
292 // string list functions
293 // ----------------------------------------------------------------------------
295 unsigned int wxChoice::GetCount() const
297 return (unsigned int)SendMessage(GetHwnd(), CB_GETCOUNT
, 0, 0);
300 int wxChoice::FindString(const wxString
& s
, bool bCase
) const
302 #if defined(__WATCOMC__) && defined(__WIN386__)
303 // For some reason, Watcom in WIN386 mode crashes in the CB_FINDSTRINGEXACT message.
304 // wxChoice::Do it the long way instead.
305 unsigned int count
= GetCount();
306 for ( unsigned int i
= 0; i
< count
; i
++ )
308 // as CB_FINDSTRINGEXACT is case insensitive, be case insensitive too
309 if (GetString(i
).IsSameAs(s
, bCase
))
315 //TODO: Evidently some MSW versions (all?) don't like empty strings
316 //passed to SendMessage, so we have to do it ourselves in that case
319 unsigned int count
= GetCount();
320 for ( unsigned int i
= 0; i
< count
; i
++ )
322 if (GetString(i
).empty())
330 // back to base class search for not native search type
331 return wxItemContainerImmutable::FindString( s
, bCase
);
335 int pos
= (int)SendMessage(GetHwnd(), CB_FINDSTRINGEXACT
,
336 (WPARAM
)-1, wxMSW_CONV_LPARAM(s
));
338 return pos
== LB_ERR
? wxNOT_FOUND
: pos
;
340 #endif // Watcom/!Watcom
343 void wxChoice::SetString(unsigned int n
, const wxString
& s
)
345 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::SetString") );
347 // we have to delete and add back the string as there is no way to change a
350 // we need to preserve the client data manually
351 void *oldData
= NULL
;
352 wxClientData
*oldObjData
= NULL
;
353 if ( HasClientUntypedData() )
354 oldData
= GetClientData(n
);
355 else if ( HasClientObjectData() )
356 oldObjData
= GetClientObject(n
);
358 // and also the selection if we're going to delete the item that was
360 const bool wasSelected
= static_cast<int>(n
) == GetSelection();
362 ::SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
363 ::SendMessage(GetHwnd(), CB_INSERTSTRING
, n
, wxMSW_CONV_LPARAM(s
) );
365 // restore the client data
367 SetClientData(n
, oldData
);
368 else if ( oldObjData
)
369 SetClientObject(n
, oldObjData
);
375 // the width could have changed so the best size needs to be recomputed
376 InvalidateBestSize();
379 wxString
wxChoice::GetString(unsigned int n
) const
381 int len
= (int)::SendMessage(GetHwnd(), CB_GETLBTEXTLEN
, n
, 0);
384 if ( len
!= CB_ERR
&& len
> 0 )
391 (LPARAM
)(wxChar
*)wxStringBuffer(str
, len
)
394 wxLogLastError(wxT("SendMessage(CB_GETLBTEXT)"));
401 // ----------------------------------------------------------------------------
403 // ----------------------------------------------------------------------------
405 void wxChoice::DoSetItemClientData(unsigned int n
, void* clientData
)
407 if ( ::SendMessage(GetHwnd(), CB_SETITEMDATA
,
408 n
, (LPARAM
)clientData
) == CB_ERR
)
410 wxLogLastError(wxT("CB_SETITEMDATA"));
414 void* wxChoice::DoGetItemClientData(unsigned int n
) const
416 LPARAM rc
= SendMessage(GetHwnd(), CB_GETITEMDATA
, n
, 0);
417 if ( rc
== CB_ERR
&& GetLastError() != ERROR_SUCCESS
)
419 wxLogLastError(wxT("CB_GETITEMDATA"));
421 // unfortunately, there is no way to return an error code to the user
428 // ----------------------------------------------------------------------------
429 // wxMSW-specific geometry management
430 // ----------------------------------------------------------------------------
435 // there is a difference between the height passed to CB_SETITEMHEIGHT and the
436 // real height of the combobox; it is probably not constant for all Windows
437 // versions/settings but right now I don't know how to find what it is so it is
438 // temporarily hardcoded to its value under XP systems with normal fonts sizes
439 const int COMBO_HEIGHT_ADJ
= 6;
441 } // anonymous namespace
443 void wxChoice::MSWUpdateVisibleHeight()
445 if ( m_heightOwn
!= wxDefaultCoord
)
447 ::SendMessage(GetHwnd(), CB_SETITEMHEIGHT
,
448 (WPARAM
)-1, m_heightOwn
- COMBO_HEIGHT_ADJ
);
452 #if wxUSE_DEFERRED_SIZING
453 void wxChoice::MSWEndDeferWindowPos()
455 // we can only set the height of the choice itself now as it is reset to
456 // default every time the control is resized
457 MSWUpdateVisibleHeight();
459 wxChoiceBase::MSWEndDeferWindowPos();
461 #endif // wxUSE_DEFERRED_SIZING
463 void wxChoice::MSWUpdateDropDownHeight()
465 // be careful to not change the width here
466 DoSetSize(wxDefaultCoord
, wxDefaultCoord
, wxDefaultCoord
, GetSize().y
,
467 wxSIZE_USE_EXISTING
);
470 void wxChoice::DoMoveWindow(int x
, int y
, int width
, int height
)
472 // here is why this is necessary: if the width is negative, the combobox
473 // window proc makes the window of the size width*height instead of
474 // interpreting height in the usual manner (meaning the height of the drop
475 // down list - usually the height specified in the call to MoveWindow()
476 // will not change the height of combo box per se)
478 // this behaviour is not documented anywhere, but this is just how it is
479 // here (NT 4.4) and, anyhow, the check shouldn't hurt - however without
480 // the check, constraints/sizers using combos may break the height
481 // constraint will have not at all the same value as expected
485 wxControl::DoMoveWindow(x
, y
, width
, height
);
488 void wxChoice::DoGetSize(int *w
, int *h
) const
490 wxControl::DoGetSize(w
, h
);
492 // this is weird: sometimes, the height returned by Windows is clearly the
493 // total height of the control including the drop down list -- but only
494 // sometimes, and sometimes it isn't so work around this here by using our
495 // own stored value if we have it
496 if ( h
&& m_heightOwn
!= wxDefaultCoord
)
500 void wxChoice::DoSetSize(int x
, int y
,
501 int width
, int height
,
504 const int heightBest
= GetBestSize().y
;
506 // we need the real height below so get the current one if it's not given
507 if ( height
== wxDefaultCoord
)
509 // height not specified, use the same as before
510 DoGetSize(NULL
, &height
);
512 else if ( height
== heightBest
)
514 // we don't need to manually manage our height, let the system use the
516 m_heightOwn
= wxDefaultCoord
;
518 else // non-default height specified
520 // set our new own height but be careful not to make it too big: the
521 // native control apparently stores it as a single byte and so setting
522 // own height to 256 pixels results in default height being used (255
524 m_heightOwn
= height
;
526 if ( m_heightOwn
> UCHAR_MAX
)
527 m_heightOwn
= UCHAR_MAX
;
528 // nor too small: see MSWUpdateVisibleHeight()
529 else if ( m_heightOwn
< COMBO_HEIGHT_ADJ
)
530 m_heightOwn
= COMBO_HEIGHT_ADJ
;
534 // the height which we must pass to Windows should be the total height of
535 // the control including the drop down list while the height given to us
536 // is, of course, just the height of the permanently visible part of it so
537 // add the drop down height to it
539 // don't make the drop down list too tall, arbitrarily limit it to 30
540 // items max and also don't make it too small if it's currently empty
541 size_t nItems
= GetCount();
542 if (!HasFlag(wxCB_SIMPLE
))
546 else if ( nItems
> 30 )
550 const int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, 0, 0);
551 int heightWithItems
= 0;
552 if (!HasFlag(wxCB_SIMPLE
))
553 // The extra item (" + 1") is required to prevent a vertical
554 // scrollbar from appearing with comctl32.dll versions earlier
555 // than 6.0 (such as found in Win2k).
556 heightWithItems
= height
+ hItem
*(nItems
+ 1);
558 heightWithItems
= SetHeightSimpleComboBox(nItems
);
561 // do resize the native control
562 wxControl::DoSetSize(x
, y
, width
, heightWithItems
, sizeFlags
);
565 // make the control itself of the requested height: notice that this
566 // must be done after changing its size or it has no effect (apparently
567 // the height is reset to default during the control layout) and that it's
568 // useless to do it when using the deferred sizing -- in this case it
569 // will be done from MSWEndDeferWindowPos()
570 #if wxUSE_DEFERRED_SIZING
571 if ( m_pendingSize
== wxDefaultSize
)
573 // not using deferred sizing, update it immediately
574 MSWUpdateVisibleHeight();
576 else // in the middle of deferred sizing
578 // we need to report the size of the visible part of the control back
579 // in GetSize() and not height stored by DoSetSize() in m_pendingSize
580 m_pendingSize
= wxSize(width
, height
);
582 #else // !wxUSE_DEFERRED_SIZING
583 // always update the visible height immediately
584 MSWUpdateVisibleHeight();
585 #endif // wxUSE_DEFERRED_SIZING
588 wxSize
wxChoice::DoGetBestSize() const
590 // find the widest string
593 const unsigned int nItems
= GetCount();
594 for ( unsigned int i
= 0; i
< nItems
; i
++ )
597 GetTextExtent(GetString(i
), &wLine
, NULL
);
598 if ( wLine
> wChoice
)
602 // give it some reasonable default value if there are no strings in the
607 // the combobox should be slightly larger than the widest string
608 wChoice
+= 5*GetCharWidth();
609 if( HasFlag( wxCB_SIMPLE
) )
611 hChoice
= SetHeightSimpleComboBox( nItems
);
614 hChoice
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(GetCharHeight());
616 wxSize
best(wChoice
, hChoice
);
621 int wxChoice::SetHeightSimpleComboBox(int nItems
) const
624 wxGetCharSize( GetHWND(), &cx
, &cy
, GetFont() );
625 int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, (WPARAM
)-1, 0);
626 return EDIT_HEIGHT_FROM_CHAR_HEIGHT( cy
) * wxMin( wxMax( nItems
, 3 ), 6 ) + hItem
- 1;
629 // ----------------------------------------------------------------------------
631 // ----------------------------------------------------------------------------
633 void wxChoice::MSWDoPopupOrDismiss(bool show
)
635 wxASSERT_MSG( !HasFlag(wxCB_SIMPLE
),
636 wxT("can't popup/dismiss the list for simple combo box") );
638 // we *must* set focus to the combobox before showing or hiding the drop
639 // down as without this we get WM_LBUTTONDOWN messages with invalid HWND
640 // when hiding it (whether programmatically or manually) resulting in a
641 // crash when we pass them to IsDialogMessage()
643 // this can be seen in the combo page of the widgets sample under Windows 7
646 ::SendMessage(GetHwnd(), CB_SHOWDROPDOWN
, show
, 0);
649 bool wxChoice::Show(bool show
)
651 if ( !wxChoiceBase::Show(show
) )
654 // When hiding the combobox, we also need to hide its popup part as it
655 // doesn't happen automatically.
656 if ( !show
&& ::SendMessage(GetHwnd(), CB_GETDROPPEDSTATE
, 0, 0) )
657 MSWDoPopupOrDismiss(false);
662 // ----------------------------------------------------------------------------
663 // MSW message handlers
664 // ----------------------------------------------------------------------------
666 WXLRESULT
wxChoice::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
672 int x
= (int)LOWORD(lParam
);
673 int y
= (int)HIWORD(lParam
);
675 // Ok, this is truly weird, but if a panel with a wxChoice
676 // loses the focus, then you get a *fake* WM_LBUTTONUP message
677 // with x = 65535 and y = 65535. Filter out this nonsense.
679 // VZ: I'd like to know how to reproduce this please...
680 if ( x
== 65535 && y
== 65535 )
685 // we have to handle both: one for the normal case and the other
687 case WM_CTLCOLOREDIT
:
688 case WM_CTLCOLORLISTBOX
:
689 case WM_CTLCOLORSTATIC
:
693 UnpackCtlColor(wParam
, lParam
, &hdc
, &hwnd
);
695 WXHBRUSH hbr
= MSWControlColor((WXHDC
)hdc
, hwnd
);
697 return (WXLRESULT
)hbr
;
698 //else: fall through to default window proc
702 return wxWindow::MSWWindowProc(nMsg
, wParam
, lParam
);
705 bool wxChoice::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
708 The native control provides a great variety in the events it sends in
709 the different selection scenarios (undoubtedly for greater amusement of
710 the programmers using it). For the reference, here are the cases when
711 the final selection is accepted (things are quite interesting when it
714 A. Selecting with just the arrows without opening the dropdown:
718 B. Opening dropdown with F4 and selecting with arrows:
720 2. many CBN_SELCHANGE while changing selection in the list
724 C. Selecting with the mouse:
726 -- no intermediate CBN_SELCHANGEs --
731 Admire the different order of messages in all of those cases, it must
732 surely have taken a lot of effort to Microsoft developers to achieve
738 // we use this value both because we don't want to track selection
739 // using CB_GETCURSEL while the dropdown is opened and because we
740 // need to reset the selection back to it if it's eventually
742 m_lastAcceptedSelection
= GetCurrentSelection();
746 // if the selection was accepted by the user, it should have been
747 // reset to wxID_NONE by CBN_SELENDOK, otherwise the selection was
748 // cancelled and we must restore the old one
749 if ( m_lastAcceptedSelection
!= wxID_NONE
)
751 SetSelection(m_lastAcceptedSelection
);
752 m_lastAcceptedSelection
= wxID_NONE
;
757 // reset it to prevent CBN_CLOSEUP from undoing the selection (it's
758 // ok to reset it now as GetCurrentSelection() will now return the
759 // same thing anyhow)
760 m_lastAcceptedSelection
= wxID_NONE
;
763 const int n
= GetSelection();
765 wxCommandEvent
event(wxEVT_COMMAND_CHOICE_SELECTED
, m_windowId
);
767 event
.SetEventObject(this);
771 event
.SetString(GetStringSelection());
772 InitCommandEventWithItems(event
, n
);
775 ProcessCommand(event
);
779 // don't handle CBN_SELENDCANCEL: just leave m_lastAcceptedSelection
780 // valid and the selection will be undone in CBN_CLOSEUP above
782 // don't handle CBN_SELCHANGE neither, we don't want to generate events
783 // while the dropdown is opened -- but do add it if we ever need this
792 WXHBRUSH
wxChoice::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
794 if ( !IsThisEnabled() )
795 return MSWControlColorDisabled(hDC
);
797 return wxChoiceBase::MSWControlColor(hDC
, hWnd
);
800 #endif // wxUSE_CHOICE && !(__SMARTPHONE__ && __WXWINCE__)