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/dynlib.h"
41 #include "wx/msw/private.h"
43 // ============================================================================
45 // ============================================================================
47 // ----------------------------------------------------------------------------
49 // ----------------------------------------------------------------------------
51 bool wxChoice::Create(wxWindow
*parent
,
55 int n
, const wxString choices
[],
57 const wxValidator
& validator
,
60 // Experience shows that wxChoice vs. wxComboBox distinction confuses
61 // quite a few people - try to help them
62 wxASSERT_MSG( !(style
& wxCB_DROPDOWN
) &&
63 !(style
& wxCB_READONLY
) &&
64 !(style
& wxCB_SIMPLE
),
65 wxT("this style flag is ignored by wxChoice, you ")
66 wxT("probably want to use a wxComboBox") );
68 return CreateAndInit(parent
, id
, pos
, size
, n
, choices
, style
,
72 bool wxChoice::CreateAndInit(wxWindow
*parent
,
76 int n
, const wxString choices
[],
78 const wxValidator
& validator
,
81 // initialize wxControl
82 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
85 // now create the real HWND
86 if ( !MSWCreateControl(wxT("COMBOBOX"), wxEmptyString
, pos
, size
) )
90 // initialize the controls contents
93 // and now we may finally size the control properly (if needed)
99 void wxChoice::SetLabel(const wxString
& label
)
101 if ( FindString(label
) == wxNOT_FOUND
)
103 // unless we explicitly do this here, CB_GETCURSEL will continue to
104 // return the index of the previously selected item which will result
105 // in wrongly replacing the value being set now with the previously
106 // value if the user simply opens and closes (without selecting
107 // anything) the combobox popup
111 wxChoiceBase::SetLabel(label
);
114 bool wxChoice::Create(wxWindow
*parent
,
118 const wxArrayString
& choices
,
120 const wxValidator
& validator
,
121 const wxString
& name
)
123 wxCArrayString
chs(choices
);
124 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
125 style
, validator
, name
);
128 bool wxChoice::MSWShouldPreProcessMessage(WXMSG
*pMsg
)
130 MSG
*msg
= (MSG
*) pMsg
;
132 // if the dropdown list is visible, don't preprocess certain keys
133 if ( msg
->message
== WM_KEYDOWN
134 && (msg
->wParam
== VK_ESCAPE
|| msg
->wParam
== VK_RETURN
) )
136 if (::SendMessage(GetHwndOf(this), CB_GETDROPPEDSTATE
, 0, 0))
142 return wxControl::MSWShouldPreProcessMessage(pMsg
);
145 WXDWORD
wxChoice::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
147 // we never have an external border
148 WXDWORD msStyle
= wxControl::MSWGetStyle
150 (style
& ~wxBORDER_MASK
) | wxBORDER_NONE
, exstyle
153 // WS_CLIPSIBLINGS is useful with wxChoice and doesn't seem to result in
155 msStyle
|= WS_CLIPSIBLINGS
;
157 // wxChoice-specific styles
158 msStyle
|= CBS_DROPDOWNLIST
| WS_HSCROLL
| WS_VSCROLL
;
159 if ( style
& wxCB_SORT
)
166 #define EP_EDITTEXT 1
171 wxChoice::GetClassDefaultAttributes(wxWindowVariant
WXUNUSED(variant
))
173 // it is important to return valid values for all attributes from here,
174 // GetXXX() below rely on this
175 wxVisualAttributes attrs
;
177 // FIXME: Use better dummy window?
178 wxWindow
* wnd
= wxTheApp
->GetTopWindow();
182 attrs
.font
= wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT
);
184 // there doesn't seem to be any way to get the text colour using themes
185 // API: TMT_TEXTCOLOR doesn't work neither for EDIT nor COMBOBOX
186 attrs
.colFg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
);
188 // NB: use EDIT, not COMBOBOX (the latter works in XP but not Vista)
189 attrs
.colBg
= wnd
->MSWGetThemeColour(L
"EDIT",
192 ThemeColourBackground
,
193 wxSYS_COLOUR_WINDOW
);
198 wxChoice::~wxChoice()
203 bool wxChoice::MSWGetComboBoxInfo(tagCOMBOBOXINFO
* info
) const
205 // TODO-Win9x: Get rid of this once we officially drop support for Win9x
206 // and just call the function directly.
207 #if wxUSE_DYNLIB_CLASS
208 typedef BOOL (WINAPI
*GetComboBoxInfo_t
)(HWND
, tagCOMBOBOXINFO
*);
209 static GetComboBoxInfo_t s_pfnGetComboBoxInfo
= NULL
;
210 static bool s_triedToLoad
= false;
211 if ( !s_triedToLoad
)
213 s_triedToLoad
= true;
214 wxLoadedDLL
dllUser32("user32.dll");
215 wxDL_INIT_FUNC(s_pfn
, GetComboBoxInfo
, dllUser32
);
218 if ( s_pfnGetComboBoxInfo
)
219 return (*s_pfnGetComboBoxInfo
)(GetHwnd(), info
) != 0;
220 #endif // wxUSE_DYNLIB_CLASS
225 // ----------------------------------------------------------------------------
226 // adding/deleting items to/from the list
227 // ----------------------------------------------------------------------------
229 int wxChoice::DoInsertItems(const wxArrayStringsAdapter
& items
,
231 void **clientData
, wxClientDataType type
)
233 MSWAllocStorage(items
, CB_INITSTORAGE
);
235 const bool append
= pos
== GetCount();
237 // use CB_ADDSTRING when appending at the end to make sure the control is
238 // resorted if it has wxCB_SORT style
239 const unsigned msg
= append
? CB_ADDSTRING
: CB_INSERTSTRING
;
245 const unsigned numItems
= items
.GetCount();
246 for ( unsigned i
= 0; i
< numItems
; ++i
)
248 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
249 if ( n
== wxNOT_FOUND
)
255 AssignNewItemClientData(n
, clientData
, i
, type
);
258 // we need to refresh our size in order to have enough space for the
261 MSWUpdateDropDownHeight();
263 InvalidateBestSize();
268 void wxChoice::DoDeleteOneItem(unsigned int n
)
270 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::Delete") );
272 SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
275 MSWUpdateDropDownHeight();
277 InvalidateBestSize();
280 void wxChoice::DoClear()
282 SendMessage(GetHwnd(), CB_RESETCONTENT
, 0, 0);
285 MSWUpdateDropDownHeight();
287 InvalidateBestSize();
290 // ----------------------------------------------------------------------------
292 // ----------------------------------------------------------------------------
294 int wxChoice::GetSelection() const
296 // if m_lastAcceptedSelection is set, it means that the dropdown is
297 // currently shown and that we want to use the last "permanent" selection
298 // instead of whatever is under the mouse pointer currently
300 // otherwise, get the selection from the control
301 return m_lastAcceptedSelection
== wxID_NONE
? GetCurrentSelection()
302 : m_lastAcceptedSelection
;
305 int wxChoice::GetCurrentSelection() const
307 return (int)SendMessage(GetHwnd(), CB_GETCURSEL
, 0, 0);
310 void wxChoice::SetSelection(int n
)
312 SendMessage(GetHwnd(), CB_SETCURSEL
, n
, 0);
315 // ----------------------------------------------------------------------------
316 // string list functions
317 // ----------------------------------------------------------------------------
319 unsigned int wxChoice::GetCount() const
321 return (unsigned int)SendMessage(GetHwnd(), CB_GETCOUNT
, 0, 0);
324 int wxChoice::FindString(const wxString
& s
, bool bCase
) const
326 #if defined(__WATCOMC__) && defined(__WIN386__)
327 // For some reason, Watcom in WIN386 mode crashes in the CB_FINDSTRINGEXACT message.
328 // wxChoice::Do it the long way instead.
329 unsigned int count
= GetCount();
330 for ( unsigned int i
= 0; i
< count
; i
++ )
332 // as CB_FINDSTRINGEXACT is case insensitive, be case insensitive too
333 if (GetString(i
).IsSameAs(s
, bCase
))
339 //TODO: Evidently some MSW versions (all?) don't like empty strings
340 //passed to SendMessage, so we have to do it ourselves in that case
343 unsigned int count
= GetCount();
344 for ( unsigned int i
= 0; i
< count
; i
++ )
346 if (GetString(i
).empty())
354 // back to base class search for not native search type
355 return wxItemContainerImmutable::FindString( s
, bCase
);
359 int pos
= (int)SendMessage(GetHwnd(), CB_FINDSTRINGEXACT
,
360 (WPARAM
)-1, wxMSW_CONV_LPARAM(s
));
362 return pos
== LB_ERR
? wxNOT_FOUND
: pos
;
364 #endif // Watcom/!Watcom
367 void wxChoice::SetString(unsigned int n
, const wxString
& s
)
369 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::SetString") );
371 // we have to delete and add back the string as there is no way to change a
374 // we need to preserve the client data manually
375 void *oldData
= NULL
;
376 wxClientData
*oldObjData
= NULL
;
377 if ( HasClientUntypedData() )
378 oldData
= GetClientData(n
);
379 else if ( HasClientObjectData() )
380 oldObjData
= GetClientObject(n
);
382 // and also the selection if we're going to delete the item that was
384 const bool wasSelected
= static_cast<int>(n
) == GetSelection();
386 ::SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
387 ::SendMessage(GetHwnd(), CB_INSERTSTRING
, n
, wxMSW_CONV_LPARAM(s
) );
389 // restore the client data
391 SetClientData(n
, oldData
);
392 else if ( oldObjData
)
393 SetClientObject(n
, oldObjData
);
399 // the width could have changed so the best size needs to be recomputed
400 InvalidateBestSize();
403 wxString
wxChoice::GetString(unsigned int n
) const
405 int len
= (int)::SendMessage(GetHwnd(), CB_GETLBTEXTLEN
, n
, 0);
408 if ( len
!= CB_ERR
&& len
> 0 )
415 (LPARAM
)(wxChar
*)wxStringBuffer(str
, len
)
418 wxLogLastError(wxT("SendMessage(CB_GETLBTEXT)"));
425 // ----------------------------------------------------------------------------
427 // ----------------------------------------------------------------------------
429 void wxChoice::DoSetItemClientData(unsigned int n
, void* clientData
)
431 if ( ::SendMessage(GetHwnd(), CB_SETITEMDATA
,
432 n
, (LPARAM
)clientData
) == CB_ERR
)
434 wxLogLastError(wxT("CB_SETITEMDATA"));
438 void* wxChoice::DoGetItemClientData(unsigned int n
) const
440 LPARAM rc
= SendMessage(GetHwnd(), CB_GETITEMDATA
, n
, 0);
441 if ( rc
== CB_ERR
&& GetLastError() != ERROR_SUCCESS
)
443 wxLogLastError(wxT("CB_GETITEMDATA"));
445 // unfortunately, there is no way to return an error code to the user
452 // ----------------------------------------------------------------------------
453 // wxMSW-specific geometry management
454 // ----------------------------------------------------------------------------
459 // there is a difference between the height passed to CB_SETITEMHEIGHT and the
460 // real height of the combobox; it is probably not constant for all Windows
461 // versions/settings but right now I don't know how to find what it is so it is
462 // temporarily hardcoded to its value under XP systems with normal fonts sizes
463 const int COMBO_HEIGHT_ADJ
= 6;
465 } // anonymous namespace
467 void wxChoice::MSWUpdateVisibleHeight()
469 if ( m_heightOwn
!= wxDefaultCoord
)
471 ::SendMessage(GetHwnd(), CB_SETITEMHEIGHT
,
472 (WPARAM
)-1, m_heightOwn
- COMBO_HEIGHT_ADJ
);
476 #if wxUSE_DEFERRED_SIZING
477 void wxChoice::MSWEndDeferWindowPos()
479 // we can only set the height of the choice itself now as it is reset to
480 // default every time the control is resized
481 MSWUpdateVisibleHeight();
483 wxChoiceBase::MSWEndDeferWindowPos();
485 #endif // wxUSE_DEFERRED_SIZING
487 void wxChoice::MSWUpdateDropDownHeight()
489 // be careful to not change the width here
490 DoSetSize(wxDefaultCoord
, wxDefaultCoord
, wxDefaultCoord
, GetSize().y
,
491 wxSIZE_USE_EXISTING
);
494 void wxChoice::DoMoveWindow(int x
, int y
, int width
, int height
)
496 // here is why this is necessary: if the width is negative, the combobox
497 // window proc makes the window of the size width*height instead of
498 // interpreting height in the usual manner (meaning the height of the drop
499 // down list - usually the height specified in the call to MoveWindow()
500 // will not change the height of combo box per se)
502 // this behaviour is not documented anywhere, but this is just how it is
503 // here (NT 4.4) and, anyhow, the check shouldn't hurt - however without
504 // the check, constraints/sizers using combos may break the height
505 // constraint will have not at all the same value as expected
509 wxControl::DoMoveWindow(x
, y
, width
, height
);
512 void wxChoice::DoGetSize(int *w
, int *h
) const
514 wxControl::DoGetSize(w
, h
);
516 // this is weird: sometimes, the height returned by Windows is clearly the
517 // total height of the control including the drop down list -- but only
518 // sometimes, and sometimes it isn't so work around this here by using our
519 // own stored value if we have it
520 if ( h
&& m_heightOwn
!= wxDefaultCoord
)
524 void wxChoice::DoSetSize(int x
, int y
,
525 int width
, int height
,
528 const int heightBest
= GetBestSize().y
;
530 // we need the real height below so get the current one if it's not given
531 if ( height
== wxDefaultCoord
)
533 // height not specified, use the same as before
534 DoGetSize(NULL
, &height
);
536 else if ( height
== heightBest
)
538 // we don't need to manually manage our height, let the system use the
540 m_heightOwn
= wxDefaultCoord
;
542 else // non-default height specified
544 // set our new own height but be careful not to make it too big: the
545 // native control apparently stores it as a single byte and so setting
546 // own height to 256 pixels results in default height being used (255
548 m_heightOwn
= height
;
550 if ( m_heightOwn
> UCHAR_MAX
)
551 m_heightOwn
= UCHAR_MAX
;
552 // nor too small: see MSWUpdateVisibleHeight()
553 else if ( m_heightOwn
< COMBO_HEIGHT_ADJ
)
554 m_heightOwn
= COMBO_HEIGHT_ADJ
;
558 // the height which we must pass to Windows should be the total height of
559 // the control including the drop down list while the height given to us
560 // is, of course, just the height of the permanently visible part of it so
561 // add the drop down height to it
563 // don't make the drop down list too tall, arbitrarily limit it to 30
564 // items max and also don't make it too small if it's currently empty
565 size_t nItems
= GetCount();
566 if (!HasFlag(wxCB_SIMPLE
))
570 else if ( nItems
> 30 )
574 const int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, 0, 0);
575 int heightWithItems
= 0;
576 if (!HasFlag(wxCB_SIMPLE
))
577 // The extra item (" + 1") is required to prevent a vertical
578 // scrollbar from appearing with comctl32.dll versions earlier
579 // than 6.0 (such as found in Win2k).
580 heightWithItems
= height
+ hItem
*(nItems
+ 1);
582 heightWithItems
= SetHeightSimpleComboBox(nItems
);
585 // do resize the native control
586 wxControl::DoSetSize(x
, y
, width
, heightWithItems
, sizeFlags
);
589 // make the control itself of the requested height: notice that this
590 // must be done after changing its size or it has no effect (apparently
591 // the height is reset to default during the control layout) and that it's
592 // useless to do it when using the deferred sizing -- in this case it
593 // will be done from MSWEndDeferWindowPos()
594 #if wxUSE_DEFERRED_SIZING
595 if ( m_pendingSize
== wxDefaultSize
)
597 // not using deferred sizing, update it immediately
598 MSWUpdateVisibleHeight();
600 else // in the middle of deferred sizing
602 // we need to report the size of the visible part of the control back
603 // in GetSize() and not height stored by DoSetSize() in m_pendingSize
604 m_pendingSize
= wxSize(width
, height
);
606 #else // !wxUSE_DEFERRED_SIZING
607 // always update the visible height immediately
608 MSWUpdateVisibleHeight();
609 #endif // wxUSE_DEFERRED_SIZING
612 wxSize
wxChoice::DoGetBestSize() const
614 // The base version returns the size of the largest string
615 return GetSizeFromTextSize(wxChoiceBase::DoGetBestSize().x
);
618 int wxChoice::SetHeightSimpleComboBox(int nItems
) const
621 wxGetCharSize( GetHWND(), &cx
, &cy
, GetFont() );
622 int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, (WPARAM
)-1, 0);
623 return EDIT_HEIGHT_FROM_CHAR_HEIGHT( cy
) * wxMin( wxMax( nItems
, 3 ), 6 ) + hItem
- 1;
626 wxSize
wxChoice::DoGetSizeFromTextSize(int xlen
, int ylen
) const
628 int cHeight
= GetCharHeight();
630 // We are interested in the difference of sizes between the whole control
631 // and its child part. I.e. arrow, separators, etc.
632 wxSize
tsize(xlen
, 0);
634 // FIXME-VC6: Only VC6 needs this guard, see WINVER definition in
635 // include/wx/msw/wrapwin.h
636 #if defined(WINVER) && WINVER >= 0x0500
637 WinStruct
<COMBOBOXINFO
> info
;
638 if ( MSWGetComboBoxInfo(&info
) )
640 tsize
.x
+= info
.rcItem
.left
+ info
.rcButton
.right
- info
.rcItem
.right
641 + info
.rcItem
.left
+ 3; // right and extra margins
643 else // Just use some rough approximation.
644 #endif // WINVER >= 0x0500
646 tsize
.x
+= 4*cHeight
;
649 // set height on our own
650 if( HasFlag( wxCB_SIMPLE
) )
651 tsize
.y
= SetHeightSimpleComboBox(GetCount());
653 tsize
.y
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cHeight
);
655 // Perhaps the user wants something different from CharHeight
657 tsize
.IncBy(0, ylen
- cHeight
);
662 // ----------------------------------------------------------------------------
664 // ----------------------------------------------------------------------------
666 void wxChoice::MSWDoPopupOrDismiss(bool show
)
668 wxASSERT_MSG( !HasFlag(wxCB_SIMPLE
),
669 wxT("can't popup/dismiss the list for simple combo box") );
671 // we *must* set focus to the combobox before showing or hiding the drop
672 // down as without this we get WM_LBUTTONDOWN messages with invalid HWND
673 // when hiding it (whether programmatically or manually) resulting in a
674 // crash when we pass them to IsDialogMessage()
676 // this can be seen in the combo page of the widgets sample under Windows 7
679 ::SendMessage(GetHwnd(), CB_SHOWDROPDOWN
, show
, 0);
682 bool wxChoice::Show(bool show
)
684 if ( !wxChoiceBase::Show(show
) )
687 // When hiding the combobox, we also need to hide its popup part as it
688 // doesn't happen automatically.
689 if ( !show
&& ::SendMessage(GetHwnd(), CB_GETDROPPEDSTATE
, 0, 0) )
690 MSWDoPopupOrDismiss(false);
695 // ----------------------------------------------------------------------------
696 // MSW message handlers
697 // ----------------------------------------------------------------------------
699 WXLRESULT
wxChoice::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
705 int x
= (int)LOWORD(lParam
);
706 int y
= (int)HIWORD(lParam
);
708 // Ok, this is truly weird, but if a panel with a wxChoice
709 // loses the focus, then you get a *fake* WM_LBUTTONUP message
710 // with x = 65535 and y = 65535. Filter out this nonsense.
712 // VZ: I'd like to know how to reproduce this please...
713 if ( x
== 65535 && y
== 65535 )
718 // we have to handle both: one for the normal case and the other
720 case WM_CTLCOLOREDIT
:
721 case WM_CTLCOLORLISTBOX
:
722 case WM_CTLCOLORSTATIC
:
726 UnpackCtlColor(wParam
, lParam
, &hdc
, &hwnd
);
728 WXHBRUSH hbr
= MSWControlColor((WXHDC
)hdc
, hwnd
);
730 return (WXLRESULT
)hbr
;
731 //else: fall through to default window proc
735 return wxWindow::MSWWindowProc(nMsg
, wParam
, lParam
);
738 bool wxChoice::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
741 The native control provides a great variety in the events it sends in
742 the different selection scenarios (undoubtedly for greater amusement of
743 the programmers using it). For the reference, here are the cases when
744 the final selection is accepted (things are quite interesting when it
747 A. Selecting with just the arrows without opening the dropdown:
751 B. Opening dropdown with F4 and selecting with arrows:
753 2. many CBN_SELCHANGE while changing selection in the list
757 C. Selecting with the mouse:
759 -- no intermediate CBN_SELCHANGEs --
764 Admire the different order of messages in all of those cases, it must
765 surely have taken a lot of effort to Microsoft developers to achieve
771 // we use this value both because we don't want to track selection
772 // using CB_GETCURSEL while the dropdown is opened and because we
773 // need to reset the selection back to it if it's eventually
775 m_lastAcceptedSelection
= GetCurrentSelection();
779 // if the selection was accepted by the user, it should have been
780 // reset to wxID_NONE by CBN_SELENDOK, otherwise the selection was
781 // cancelled and we must restore the old one
782 if ( m_lastAcceptedSelection
!= wxID_NONE
)
784 SetSelection(m_lastAcceptedSelection
);
785 m_lastAcceptedSelection
= wxID_NONE
;
790 // reset it to prevent CBN_CLOSEUP from undoing the selection (it's
791 // ok to reset it now as GetCurrentSelection() will now return the
792 // same thing anyhow)
793 m_lastAcceptedSelection
= wxID_NONE
;
796 const int n
= GetSelection();
798 wxCommandEvent
event(wxEVT_COMMAND_CHOICE_SELECTED
, m_windowId
);
800 event
.SetEventObject(this);
804 event
.SetString(GetStringSelection());
805 InitCommandEventWithItems(event
, n
);
808 ProcessCommand(event
);
812 // don't handle CBN_SELENDCANCEL: just leave m_lastAcceptedSelection
813 // valid and the selection will be undone in CBN_CLOSEUP above
815 // don't handle CBN_SELCHANGE neither, we don't want to generate events
816 // while the dropdown is opened -- but do add it if we ever need this
825 WXHBRUSH
wxChoice::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
827 if ( !IsThisEnabled() )
828 return MSWControlColorDisabled(hDC
);
830 return wxChoiceBase::MSWControlColor(hDC
, hWnd
);
833 #endif // wxUSE_CHOICE && !(__SMARTPHONE__ && __WXWINCE__)