1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/choice.cpp
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin to derive from wxChoiceBase
7 // Copyright: (c) Julian Smart
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
26 #if wxUSE_CHOICE && !(defined(__SMARTPHONE__) && defined(__WXWINCE__))
28 #include "wx/choice.h"
35 #include "wx/settings.h"
38 #include "wx/dynlib.h"
40 #include "wx/msw/private.h"
42 // ============================================================================
44 // ============================================================================
46 // ----------------------------------------------------------------------------
48 // ----------------------------------------------------------------------------
50 bool wxChoice::Create(wxWindow
*parent
,
54 int n
, const wxString choices
[],
56 const wxValidator
& validator
,
59 // Experience shows that wxChoice vs. wxComboBox distinction confuses
60 // quite a few people - try to help them
61 wxASSERT_MSG( !(style
& wxCB_DROPDOWN
) &&
62 !(style
& wxCB_READONLY
) &&
63 !(style
& wxCB_SIMPLE
),
64 wxT("this style flag is ignored by wxChoice, you ")
65 wxT("probably want to use a wxComboBox") );
67 return CreateAndInit(parent
, id
, pos
, size
, n
, choices
, style
,
71 bool wxChoice::CreateAndInit(wxWindow
*parent
,
75 int n
, const wxString choices
[],
77 const wxValidator
& validator
,
80 // initialize wxControl
81 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
84 // now create the real HWND
85 if ( !MSWCreateControl(wxT("COMBOBOX"), wxEmptyString
, pos
, size
) )
89 // initialize the controls contents
92 // and now we may finally size the control properly (if needed)
98 void wxChoice::SetLabel(const wxString
& label
)
100 if ( FindString(label
) == wxNOT_FOUND
)
102 // unless we explicitly do this here, CB_GETCURSEL will continue to
103 // return the index of the previously selected item which will result
104 // in wrongly replacing the value being set now with the previously
105 // value if the user simply opens and closes (without selecting
106 // anything) the combobox popup
110 wxChoiceBase::SetLabel(label
);
113 bool wxChoice::Create(wxWindow
*parent
,
117 const wxArrayString
& choices
,
119 const wxValidator
& validator
,
120 const wxString
& name
)
122 wxCArrayString
chs(choices
);
123 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
124 style
, validator
, name
);
127 bool wxChoice::MSWShouldPreProcessMessage(WXMSG
*pMsg
)
129 MSG
*msg
= (MSG
*) pMsg
;
131 // if the dropdown list is visible, don't preprocess certain keys
132 if ( msg
->message
== WM_KEYDOWN
133 && (msg
->wParam
== VK_ESCAPE
|| msg
->wParam
== VK_RETURN
) )
135 if (::SendMessage(GetHwndOf(this), CB_GETDROPPEDSTATE
, 0, 0))
141 return wxControl::MSWShouldPreProcessMessage(pMsg
);
144 WXDWORD
wxChoice::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
146 // we never have an external border
147 WXDWORD msStyle
= wxControl::MSWGetStyle
149 (style
& ~wxBORDER_MASK
) | wxBORDER_NONE
, exstyle
152 // WS_CLIPSIBLINGS is useful with wxChoice and doesn't seem to result in
154 msStyle
|= WS_CLIPSIBLINGS
;
156 // wxChoice-specific styles
157 msStyle
|= CBS_DROPDOWNLIST
| WS_HSCROLL
| WS_VSCROLL
;
158 if ( style
& wxCB_SORT
)
165 #define EP_EDITTEXT 1
170 wxChoice::GetClassDefaultAttributes(wxWindowVariant
WXUNUSED(variant
))
172 // it is important to return valid values for all attributes from here,
173 // GetXXX() below rely on this
174 wxVisualAttributes attrs
;
176 // FIXME: Use better dummy window?
177 wxWindow
* wnd
= wxTheApp
->GetTopWindow();
181 attrs
.font
= wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT
);
183 // there doesn't seem to be any way to get the text colour using themes
184 // API: TMT_TEXTCOLOR doesn't work neither for EDIT nor COMBOBOX
185 attrs
.colFg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
);
187 // NB: use EDIT, not COMBOBOX (the latter works in XP but not Vista)
188 attrs
.colBg
= wnd
->MSWGetThemeColour(L
"EDIT",
191 ThemeColourBackground
,
192 wxSYS_COLOUR_WINDOW
);
197 wxChoice::~wxChoice()
202 bool wxChoice::MSWGetComboBoxInfo(tagCOMBOBOXINFO
* info
) const
204 // TODO-Win9x: Get rid of this once we officially drop support for Win9x
205 // and just call the function directly.
206 #if wxUSE_DYNLIB_CLASS
207 typedef BOOL (WINAPI
*GetComboBoxInfo_t
)(HWND
, tagCOMBOBOXINFO
*);
208 static GetComboBoxInfo_t s_pfnGetComboBoxInfo
= NULL
;
209 static bool s_triedToLoad
= false;
210 if ( !s_triedToLoad
)
212 s_triedToLoad
= true;
213 wxLoadedDLL
dllUser32("user32.dll");
214 wxDL_INIT_FUNC(s_pfn
, GetComboBoxInfo
, dllUser32
);
217 if ( s_pfnGetComboBoxInfo
)
218 return (*s_pfnGetComboBoxInfo
)(GetHwnd(), info
) != 0;
219 #endif // wxUSE_DYNLIB_CLASS
224 // ----------------------------------------------------------------------------
225 // adding/deleting items to/from the list
226 // ----------------------------------------------------------------------------
228 int wxChoice::DoInsertItems(const wxArrayStringsAdapter
& items
,
230 void **clientData
, wxClientDataType type
)
232 MSWAllocStorage(items
, CB_INITSTORAGE
);
234 const bool append
= pos
== GetCount();
236 // use CB_ADDSTRING when appending at the end to make sure the control is
237 // resorted if it has wxCB_SORT style
238 const unsigned msg
= append
? CB_ADDSTRING
: CB_INSERTSTRING
;
244 const unsigned numItems
= items
.GetCount();
245 for ( unsigned i
= 0; i
< numItems
; ++i
)
247 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
248 if ( n
== wxNOT_FOUND
)
254 AssignNewItemClientData(n
, clientData
, i
, type
);
257 // we need to refresh our size in order to have enough space for the
260 MSWUpdateDropDownHeight();
262 InvalidateBestSize();
267 void wxChoice::DoDeleteOneItem(unsigned int n
)
269 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::Delete") );
271 SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
274 MSWUpdateDropDownHeight();
276 InvalidateBestSize();
279 void wxChoice::DoClear()
281 SendMessage(GetHwnd(), CB_RESETCONTENT
, 0, 0);
284 MSWUpdateDropDownHeight();
286 InvalidateBestSize();
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
293 int wxChoice::GetSelection() const
295 // if m_lastAcceptedSelection is set, it means that the dropdown is
296 // currently shown and that we want to use the last "permanent" selection
297 // instead of whatever is under the mouse pointer currently
299 // otherwise, get the selection from the control
300 return m_lastAcceptedSelection
== wxID_NONE
? GetCurrentSelection()
301 : m_lastAcceptedSelection
;
304 int wxChoice::GetCurrentSelection() const
306 return (int)SendMessage(GetHwnd(), CB_GETCURSEL
, 0, 0);
309 void wxChoice::SetSelection(int n
)
311 SendMessage(GetHwnd(), CB_SETCURSEL
, n
, 0);
314 // ----------------------------------------------------------------------------
315 // string list functions
316 // ----------------------------------------------------------------------------
318 unsigned int wxChoice::GetCount() const
320 return (unsigned int)SendMessage(GetHwnd(), CB_GETCOUNT
, 0, 0);
323 int wxChoice::FindString(const wxString
& s
, bool bCase
) const
325 #if defined(__WATCOMC__) && defined(__WIN386__)
326 // For some reason, Watcom in WIN386 mode crashes in the CB_FINDSTRINGEXACT message.
327 // wxChoice::Do it the long way instead.
328 unsigned int count
= GetCount();
329 for ( unsigned int i
= 0; i
< count
; i
++ )
331 // as CB_FINDSTRINGEXACT is case insensitive, be case insensitive too
332 if (GetString(i
).IsSameAs(s
, bCase
))
338 //TODO: Evidently some MSW versions (all?) don't like empty strings
339 //passed to SendMessage, so we have to do it ourselves in that case
342 unsigned int count
= GetCount();
343 for ( unsigned int i
= 0; i
< count
; i
++ )
345 if (GetString(i
).empty())
353 // back to base class search for not native search type
354 return wxItemContainerImmutable::FindString( s
, bCase
);
358 int pos
= (int)SendMessage(GetHwnd(), CB_FINDSTRINGEXACT
,
359 (WPARAM
)-1, wxMSW_CONV_LPARAM(s
));
361 return pos
== LB_ERR
? wxNOT_FOUND
: pos
;
363 #endif // Watcom/!Watcom
366 void wxChoice::SetString(unsigned int n
, const wxString
& s
)
368 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::SetString") );
370 // we have to delete and add back the string as there is no way to change a
373 // we need to preserve the client data manually
374 void *oldData
= NULL
;
375 wxClientData
*oldObjData
= NULL
;
376 if ( HasClientUntypedData() )
377 oldData
= GetClientData(n
);
378 else if ( HasClientObjectData() )
379 oldObjData
= GetClientObject(n
);
381 // and also the selection if we're going to delete the item that was
383 const bool wasSelected
= static_cast<int>(n
) == GetSelection();
385 ::SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
386 ::SendMessage(GetHwnd(), CB_INSERTSTRING
, n
, wxMSW_CONV_LPARAM(s
) );
388 // restore the client data
390 SetClientData(n
, oldData
);
391 else if ( oldObjData
)
392 SetClientObject(n
, oldObjData
);
398 // the width could have changed so the best size needs to be recomputed
399 InvalidateBestSize();
402 wxString
wxChoice::GetString(unsigned int n
) const
404 int len
= (int)::SendMessage(GetHwnd(), CB_GETLBTEXTLEN
, n
, 0);
407 if ( len
!= CB_ERR
&& len
> 0 )
414 (LPARAM
)(wxChar
*)wxStringBuffer(str
, len
)
417 wxLogLastError(wxT("SendMessage(CB_GETLBTEXT)"));
424 // ----------------------------------------------------------------------------
426 // ----------------------------------------------------------------------------
428 void wxChoice::DoSetItemClientData(unsigned int n
, void* clientData
)
430 if ( ::SendMessage(GetHwnd(), CB_SETITEMDATA
,
431 n
, (LPARAM
)clientData
) == CB_ERR
)
433 wxLogLastError(wxT("CB_SETITEMDATA"));
437 void* wxChoice::DoGetItemClientData(unsigned int n
) const
439 LPARAM rc
= SendMessage(GetHwnd(), CB_GETITEMDATA
, n
, 0);
440 if ( rc
== CB_ERR
&& GetLastError() != ERROR_SUCCESS
)
442 wxLogLastError(wxT("CB_GETITEMDATA"));
444 // unfortunately, there is no way to return an error code to the user
451 // ----------------------------------------------------------------------------
452 // wxMSW-specific geometry management
453 // ----------------------------------------------------------------------------
458 // there is a difference between the height passed to CB_SETITEMHEIGHT and the
459 // real height of the combobox; it is probably not constant for all Windows
460 // versions/settings but right now I don't know how to find what it is so it is
461 // temporarily hardcoded to its value under XP systems with normal fonts sizes
462 const int COMBO_HEIGHT_ADJ
= 6;
464 } // anonymous namespace
466 void wxChoice::MSWUpdateVisibleHeight()
468 if ( m_heightOwn
!= wxDefaultCoord
)
470 ::SendMessage(GetHwnd(), CB_SETITEMHEIGHT
,
471 (WPARAM
)-1, m_heightOwn
- COMBO_HEIGHT_ADJ
);
475 #if wxUSE_DEFERRED_SIZING
476 void wxChoice::MSWEndDeferWindowPos()
478 // we can only set the height of the choice itself now as it is reset to
479 // default every time the control is resized
480 MSWUpdateVisibleHeight();
482 wxChoiceBase::MSWEndDeferWindowPos();
484 #endif // wxUSE_DEFERRED_SIZING
486 void wxChoice::MSWUpdateDropDownHeight()
488 // be careful to not change the width here
489 DoSetSize(wxDefaultCoord
, wxDefaultCoord
, wxDefaultCoord
, GetSize().y
,
490 wxSIZE_USE_EXISTING
);
493 void wxChoice::DoMoveWindow(int x
, int y
, int width
, int height
)
495 // here is why this is necessary: if the width is negative, the combobox
496 // window proc makes the window of the size width*height instead of
497 // interpreting height in the usual manner (meaning the height of the drop
498 // down list - usually the height specified in the call to MoveWindow()
499 // will not change the height of combo box per se)
501 // this behaviour is not documented anywhere, but this is just how it is
502 // here (NT 4.4) and, anyhow, the check shouldn't hurt - however without
503 // the check, constraints/sizers using combos may break the height
504 // constraint will have not at all the same value as expected
508 wxControl::DoMoveWindow(x
, y
, width
, height
);
511 void wxChoice::DoGetSize(int *w
, int *h
) const
513 wxControl::DoGetSize(w
, h
);
515 // this is weird: sometimes, the height returned by Windows is clearly the
516 // total height of the control including the drop down list -- but only
517 // sometimes, and sometimes it isn't so work around this here by using our
518 // own stored value if we have it
519 if ( h
&& m_heightOwn
!= wxDefaultCoord
)
523 void wxChoice::DoSetSize(int x
, int y
,
524 int width
, int height
,
527 const int heightBest
= GetBestSize().y
;
529 // we need the real height below so get the current one if it's not given
530 if ( height
== wxDefaultCoord
)
532 // height not specified, use the same as before
533 DoGetSize(NULL
, &height
);
535 else if ( height
== heightBest
)
537 // we don't need to manually manage our height, let the system use the
539 m_heightOwn
= wxDefaultCoord
;
541 else // non-default height specified
543 // set our new own height but be careful not to make it too big: the
544 // native control apparently stores it as a single byte and so setting
545 // own height to 256 pixels results in default height being used (255
547 m_heightOwn
= height
;
549 if ( m_heightOwn
> UCHAR_MAX
)
550 m_heightOwn
= UCHAR_MAX
;
551 // nor too small: see MSWUpdateVisibleHeight()
552 else if ( m_heightOwn
< COMBO_HEIGHT_ADJ
)
553 m_heightOwn
= COMBO_HEIGHT_ADJ
;
557 // the height which we must pass to Windows should be the total height of
558 // the control including the drop down list while the height given to us
559 // is, of course, just the height of the permanently visible part of it so
560 // add the drop down height to it
562 // don't make the drop down list too tall, arbitrarily limit it to 30
563 // items max and also don't make it too small if it's currently empty
564 size_t nItems
= GetCount();
565 if (!HasFlag(wxCB_SIMPLE
))
569 else if ( nItems
> 30 )
573 const int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, 0, 0);
574 int heightWithItems
= 0;
575 if (!HasFlag(wxCB_SIMPLE
))
576 // The extra item (" + 1") is required to prevent a vertical
577 // scrollbar from appearing with comctl32.dll versions earlier
578 // than 6.0 (such as found in Win2k).
579 heightWithItems
= height
+ hItem
*(nItems
+ 1);
581 heightWithItems
= SetHeightSimpleComboBox(nItems
);
584 // do resize the native control
585 wxControl::DoSetSize(x
, y
, width
, heightWithItems
, sizeFlags
);
588 // make the control itself of the requested height: notice that this
589 // must be done after changing its size or it has no effect (apparently
590 // the height is reset to default during the control layout) and that it's
591 // useless to do it when using the deferred sizing -- in this case it
592 // will be done from MSWEndDeferWindowPos()
593 #if wxUSE_DEFERRED_SIZING
594 if ( m_pendingSize
== wxDefaultSize
)
596 // not using deferred sizing, update it immediately
597 MSWUpdateVisibleHeight();
599 else // in the middle of deferred sizing
601 // we need to report the size of the visible part of the control back
602 // in GetSize() and not height stored by DoSetSize() in m_pendingSize
603 m_pendingSize
= wxSize(width
, height
);
605 #else // !wxUSE_DEFERRED_SIZING
606 // always update the visible height immediately
607 MSWUpdateVisibleHeight();
608 #endif // wxUSE_DEFERRED_SIZING
611 wxSize
wxChoice::DoGetBestSize() const
613 // The base version returns the size of the largest string
614 return GetSizeFromTextSize(wxChoiceBase::DoGetBestSize().x
);
617 int wxChoice::SetHeightSimpleComboBox(int nItems
) const
620 wxGetCharSize( GetHWND(), &cx
, &cy
, GetFont() );
621 int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, (WPARAM
)-1, 0);
622 return EDIT_HEIGHT_FROM_CHAR_HEIGHT( cy
) * wxMin( wxMax( nItems
, 3 ), 6 ) + hItem
- 1;
625 wxSize
wxChoice::DoGetSizeFromTextSize(int xlen
, int ylen
) const
627 int cHeight
= GetCharHeight();
629 // We are interested in the difference of sizes between the whole control
630 // and its child part. I.e. arrow, separators, etc.
631 wxSize
tsize(xlen
, 0);
633 // FIXME-VC6: Only VC6 needs this guard, see WINVER definition in
634 // include/wx/msw/wrapwin.h
635 #if defined(WINVER) && WINVER >= 0x0500
636 WinStruct
<COMBOBOXINFO
> info
;
637 if ( MSWGetComboBoxInfo(&info
) )
639 tsize
.x
+= info
.rcItem
.left
+ info
.rcButton
.right
- info
.rcItem
.right
640 + info
.rcItem
.left
+ 3; // right and extra margins
642 else // Just use some rough approximation.
643 #endif // WINVER >= 0x0500
645 tsize
.x
+= 4*cHeight
;
648 // set height on our own
649 if( HasFlag( wxCB_SIMPLE
) )
650 tsize
.y
= SetHeightSimpleComboBox(GetCount());
652 tsize
.y
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cHeight
);
654 // Perhaps the user wants something different from CharHeight
656 tsize
.IncBy(0, ylen
- cHeight
);
661 // ----------------------------------------------------------------------------
663 // ----------------------------------------------------------------------------
665 void wxChoice::MSWDoPopupOrDismiss(bool show
)
667 wxASSERT_MSG( !HasFlag(wxCB_SIMPLE
),
668 wxT("can't popup/dismiss the list for simple combo box") );
670 // we *must* set focus to the combobox before showing or hiding the drop
671 // down as without this we get WM_LBUTTONDOWN messages with invalid HWND
672 // when hiding it (whether programmatically or manually) resulting in a
673 // crash when we pass them to IsDialogMessage()
675 // this can be seen in the combo page of the widgets sample under Windows 7
678 ::SendMessage(GetHwnd(), CB_SHOWDROPDOWN
, show
, 0);
681 bool wxChoice::Show(bool show
)
683 if ( !wxChoiceBase::Show(show
) )
686 // When hiding the combobox, we also need to hide its popup part as it
687 // doesn't happen automatically.
688 if ( !show
&& ::SendMessage(GetHwnd(), CB_GETDROPPEDSTATE
, 0, 0) )
689 MSWDoPopupOrDismiss(false);
694 // ----------------------------------------------------------------------------
695 // MSW message handlers
696 // ----------------------------------------------------------------------------
698 WXLRESULT
wxChoice::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
704 int x
= (int)LOWORD(lParam
);
705 int y
= (int)HIWORD(lParam
);
707 // Ok, this is truly weird, but if a panel with a wxChoice
708 // loses the focus, then you get a *fake* WM_LBUTTONUP message
709 // with x = 65535 and y = 65535. Filter out this nonsense.
711 // VZ: I'd like to know how to reproduce this please...
712 if ( x
== 65535 && y
== 65535 )
717 // we have to handle both: one for the normal case and the other
719 case WM_CTLCOLOREDIT
:
720 case WM_CTLCOLORLISTBOX
:
721 case WM_CTLCOLORSTATIC
:
725 UnpackCtlColor(wParam
, lParam
, &hdc
, &hwnd
);
727 WXHBRUSH hbr
= MSWControlColor((WXHDC
)hdc
, hwnd
);
729 return (WXLRESULT
)hbr
;
730 //else: fall through to default window proc
734 return wxWindow::MSWWindowProc(nMsg
, wParam
, lParam
);
737 bool wxChoice::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
740 The native control provides a great variety in the events it sends in
741 the different selection scenarios (undoubtedly for greater amusement of
742 the programmers using it). Here are the different cases:
744 A. Selecting with just the arrows without opening the dropdown:
748 B. Opening dropdown with F4 and selecting with arrows:
750 2. many CBN_SELCHANGE while changing selection in the list
754 C. Selecting with the mouse:
756 -- no intermediate CBN_SELCHANGEs --
761 Admire the different order of messages in all of those cases, it must
762 surely have taken a lot of effort to Microsoft developers to achieve
765 Additionally, notice that CBN_SELENDCANCEL doesn't seem to actually
766 cancel anything, if we get CBN_SELCHANGE before it, as it happens in
767 the case (B), the selection is still accepted. This doesn't make much
768 sense and directly contradicts MSDN documentation but is how the native
769 comboboxes behave and so we do the same thing.
774 // we use this value both because we don't want to track selection
775 // using CB_GETCURSEL while the dropdown is opened and because we
776 // need to reset the selection back to it if it's eventually
778 m_lastAcceptedSelection
= GetCurrentSelection();
782 if ( m_pendingSelection
!= wxID_NONE
)
784 // This can only happen in the case (B), so set the item
785 // selected in the drop down as our real selection.
786 SendSelectionChangedEvent(wxEVT_CHOICE
);
787 m_pendingSelection
= wxID_NONE
;
792 // Reset the variables to prevent CBN_CLOSEUP from doing anything,
793 // it's not needed if we do get CBN_SELENDOK.
794 m_lastAcceptedSelection
=
795 m_pendingSelection
= wxID_NONE
;
797 SendSelectionChangedEvent(wxEVT_CHOICE
);
801 // If we get this event after CBN_SELENDOK, i.e. cases (A) or (C)
802 // above, we don't have anything to do. But in the case (B) we need
803 // to remember that the selection should really change once the
804 // drop down is closed.
805 if ( m_lastAcceptedSelection
!= wxID_NONE
)
806 m_pendingSelection
= GetCurrentSelection();
809 case CBN_SELENDCANCEL
:
810 // Do not reset m_pendingSelection here -- it would make sense but,
811 // as described above, native controls keep the selection even when
812 // closing the drop down by pressing Escape or TAB, so conform to
814 m_lastAcceptedSelection
= wxID_NONE
;
824 WXHBRUSH
wxChoice::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
826 if ( !IsThisEnabled() )
827 return MSWControlColorDisabled(hDC
);
829 return wxChoiceBase::MSWControlColor(hDC
, hWnd
);
832 #endif // wxUSE_CHOICE && !(__SMARTPHONE__ && __WXWINCE__)