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
89 for ( int i
= 0; i
< n
; i
++ )
94 // and now we may finally size the control properly (if needed)
100 void wxChoice::SetLabel(const wxString
& label
)
102 if ( FindString(label
) == wxNOT_FOUND
)
104 // unless we explicitly do this here, CB_GETCURSEL will continue to
105 // return the index of the previously selected item which will result
106 // in wrongly replacing the value being set now with the previously
107 // value if the user simply opens and closes (without selecting
108 // anything) the combobox popup
112 wxChoiceBase::SetLabel(label
);
115 bool wxChoice::Create(wxWindow
*parent
,
119 const wxArrayString
& choices
,
121 const wxValidator
& validator
,
122 const wxString
& name
)
124 wxCArrayString
chs(choices
);
125 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
126 style
, validator
, name
);
129 bool wxChoice::MSWShouldPreProcessMessage(WXMSG
*pMsg
)
131 MSG
*msg
= (MSG
*) pMsg
;
133 // if the dropdown list is visible, don't preprocess certain keys
134 if ( msg
->message
== WM_KEYDOWN
135 && (msg
->wParam
== VK_ESCAPE
|| msg
->wParam
== VK_RETURN
) )
137 if (::SendMessage(GetHwndOf(this), CB_GETDROPPEDSTATE
, 0, 0))
143 return wxControl::MSWShouldPreProcessMessage(pMsg
);
146 WXDWORD
wxChoice::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
148 // we never have an external border
149 WXDWORD msStyle
= wxControl::MSWGetStyle
151 (style
& ~wxBORDER_MASK
) | wxBORDER_NONE
, exstyle
154 // WS_CLIPSIBLINGS is useful with wxChoice and doesn't seem to result in
156 msStyle
|= WS_CLIPSIBLINGS
;
158 // wxChoice-specific styles
159 msStyle
|= CBS_DROPDOWNLIST
| WS_HSCROLL
| WS_VSCROLL
;
160 if ( style
& wxCB_SORT
)
167 #define EP_EDITTEXT 1
172 wxChoice::GetClassDefaultAttributes(wxWindowVariant
WXUNUSED(variant
))
174 // it is important to return valid values for all attributes from here,
175 // GetXXX() below rely on this
176 wxVisualAttributes attrs
;
178 // FIXME: Use better dummy window?
179 wxWindow
* wnd
= wxTheApp
->GetTopWindow();
183 attrs
.font
= wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT
);
185 // there doesn't seem to be any way to get the text colour using themes
186 // API: TMT_TEXTCOLOR doesn't work neither for EDIT nor COMBOBOX
187 attrs
.colFg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
);
189 // NB: use EDIT, not COMBOBOX (the latter works in XP but not Vista)
190 attrs
.colBg
= wnd
->MSWGetThemeColour(L
"EDIT",
193 ThemeColourBackground
,
194 wxSYS_COLOUR_WINDOW
);
199 wxChoice::~wxChoice()
204 // ----------------------------------------------------------------------------
205 // adding/deleting items to/from the list
206 // ----------------------------------------------------------------------------
208 int wxChoice::DoInsertItems(const wxArrayStringsAdapter
& items
,
210 void **clientData
, wxClientDataType type
)
212 MSWAllocStorage(items
, CB_INITSTORAGE
);
214 const bool append
= pos
== GetCount();
216 // use CB_ADDSTRING when appending at the end to make sure the control is
217 // resorted if it has wxCB_SORT style
218 const unsigned msg
= append
? CB_ADDSTRING
: CB_INSERTSTRING
;
224 const unsigned numItems
= items
.GetCount();
225 for ( unsigned i
= 0; i
< numItems
; ++i
)
227 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
228 if ( n
== wxNOT_FOUND
)
234 AssignNewItemClientData(n
, clientData
, i
, type
);
237 // we need to refresh our size in order to have enough space for the
240 MSWUpdateDropDownHeight();
242 InvalidateBestSize();
247 void wxChoice::DoDeleteOneItem(unsigned int n
)
249 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::Delete") );
251 SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
254 MSWUpdateDropDownHeight();
256 InvalidateBestSize();
259 void wxChoice::DoClear()
261 SendMessage(GetHwnd(), CB_RESETCONTENT
, 0, 0);
264 MSWUpdateDropDownHeight();
266 InvalidateBestSize();
269 // ----------------------------------------------------------------------------
271 // ----------------------------------------------------------------------------
273 int wxChoice::GetSelection() const
275 // if m_lastAcceptedSelection is set, it means that the dropdown is
276 // currently shown and that we want to use the last "permanent" selection
277 // instead of whatever is under the mouse pointer currently
279 // otherwise, get the selection from the control
280 return m_lastAcceptedSelection
== wxID_NONE
? GetCurrentSelection()
281 : m_lastAcceptedSelection
;
284 int wxChoice::GetCurrentSelection() const
286 return (int)SendMessage(GetHwnd(), CB_GETCURSEL
, 0, 0);
289 void wxChoice::SetSelection(int n
)
291 SendMessage(GetHwnd(), CB_SETCURSEL
, n
, 0);
294 // ----------------------------------------------------------------------------
295 // string list functions
296 // ----------------------------------------------------------------------------
298 unsigned int wxChoice::GetCount() const
300 return (unsigned int)SendMessage(GetHwnd(), CB_GETCOUNT
, 0, 0);
303 int wxChoice::FindString(const wxString
& s
, bool bCase
) const
305 #if defined(__WATCOMC__) && defined(__WIN386__)
306 // For some reason, Watcom in WIN386 mode crashes in the CB_FINDSTRINGEXACT message.
307 // wxChoice::Do it the long way instead.
308 unsigned int count
= GetCount();
309 for ( unsigned int i
= 0; i
< count
; i
++ )
311 // as CB_FINDSTRINGEXACT is case insensitive, be case insensitive too
312 if (GetString(i
).IsSameAs(s
, bCase
))
318 //TODO: Evidently some MSW versions (all?) don't like empty strings
319 //passed to SendMessage, so we have to do it ourselves in that case
322 unsigned int count
= GetCount();
323 for ( unsigned int i
= 0; i
< count
; i
++ )
325 if (GetString(i
).empty())
333 // back to base class search for not native search type
334 return wxItemContainerImmutable::FindString( s
, bCase
);
338 int pos
= (int)SendMessage(GetHwnd(), CB_FINDSTRINGEXACT
,
339 (WPARAM
)-1, (LPARAM
)s
.wx_str());
341 return pos
== LB_ERR
? wxNOT_FOUND
: pos
;
343 #endif // Watcom/!Watcom
346 void wxChoice::SetString(unsigned int n
, const wxString
& s
)
348 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::SetString") );
350 // we have to delete and add back the string as there is no way to change a
353 // we need to preserve the client data manually
354 void *oldData
= NULL
;
355 wxClientData
*oldObjData
= NULL
;
356 if ( HasClientUntypedData() )
357 oldData
= GetClientData(n
);
358 else if ( HasClientObjectData() )
359 oldObjData
= GetClientObject(n
);
361 ::SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
362 ::SendMessage(GetHwnd(), CB_INSERTSTRING
, n
, (LPARAM
)s
.wx_str() );
364 // restore the client data
366 SetClientData(n
, oldData
);
367 else if ( oldObjData
)
368 SetClientObject(n
, oldObjData
);
370 InvalidateBestSize();
373 wxString
wxChoice::GetString(unsigned int n
) const
375 int len
= (int)::SendMessage(GetHwnd(), CB_GETLBTEXTLEN
, n
, 0);
378 if ( len
!= CB_ERR
&& len
> 0 )
385 (LPARAM
)(wxChar
*)wxStringBuffer(str
, len
)
388 wxLogLastError(wxT("SendMessage(CB_GETLBTEXT)"));
395 // ----------------------------------------------------------------------------
397 // ----------------------------------------------------------------------------
399 void wxChoice::DoSetItemClientData(unsigned int n
, void* clientData
)
401 if ( ::SendMessage(GetHwnd(), CB_SETITEMDATA
,
402 n
, (LPARAM
)clientData
) == CB_ERR
)
404 wxLogLastError(wxT("CB_SETITEMDATA"));
408 void* wxChoice::DoGetItemClientData(unsigned int n
) const
410 LPARAM rc
= SendMessage(GetHwnd(), CB_GETITEMDATA
, n
, 0);
413 wxLogLastError(wxT("CB_GETITEMDATA"));
415 // unfortunately, there is no way to return an error code to the user
422 // ----------------------------------------------------------------------------
423 // wxMSW-specific geometry management
424 // ----------------------------------------------------------------------------
429 // there is a difference between the height passed to CB_SETITEMHEIGHT and the
430 // real height of the combobox; it is probably not constant for all Windows
431 // versions/settings but right now I don't know how to find what it is so it is
432 // temporarily hardcoded to its value under XP systems with normal fonts sizes
433 const int COMBO_HEIGHT_ADJ
= 6;
435 } // anonymous namespace
437 void wxChoice::MSWUpdateVisibleHeight()
439 if ( m_heightOwn
!= wxDefaultCoord
)
441 ::SendMessage(GetHwnd(), CB_SETITEMHEIGHT
,
442 (WPARAM
)-1, m_heightOwn
- COMBO_HEIGHT_ADJ
);
446 #if wxUSE_DEFERRED_SIZING
447 void wxChoice::MSWEndDeferWindowPos()
449 // we can only set the height of the choice itself now as it is reset to
450 // default every time the control is resized
451 MSWUpdateVisibleHeight();
453 wxChoiceBase::MSWEndDeferWindowPos();
455 #endif // wxUSE_DEFERRED_SIZING
457 void wxChoice::MSWUpdateDropDownHeight()
459 // be careful to not change the width here
460 DoSetSize(wxDefaultCoord
, wxDefaultCoord
, wxDefaultCoord
, GetSize().y
,
461 wxSIZE_USE_EXISTING
);
464 void wxChoice::DoMoveWindow(int x
, int y
, int width
, int height
)
466 // here is why this is necessary: if the width is negative, the combobox
467 // window proc makes the window of the size width*height instead of
468 // interpreting height in the usual manner (meaning the height of the drop
469 // down list - usually the height specified in the call to MoveWindow()
470 // will not change the height of combo box per se)
472 // this behaviour is not documented anywhere, but this is just how it is
473 // here (NT 4.4) and, anyhow, the check shouldn't hurt - however without
474 // the check, constraints/sizers using combos may break the height
475 // constraint will have not at all the same value as expected
479 wxControl::DoMoveWindow(x
, y
, width
, height
);
482 void wxChoice::DoGetSize(int *w
, int *h
) const
484 wxControl::DoGetSize(w
, h
);
486 // this is weird: sometimes, the height returned by Windows is clearly the
487 // total height of the control including the drop down list -- but only
488 // sometimes, and sometimes it isn't so work around this here by using our
489 // own stored value if we have it
490 if ( h
&& m_heightOwn
!= wxDefaultCoord
)
494 void wxChoice::DoSetSize(int x
, int y
,
495 int width
, int height
,
498 const int heightBest
= GetBestSize().y
;
500 // we need the real height below so get the current one if it's not given
501 if ( height
== wxDefaultCoord
)
503 // height not specified, use the same as before
504 DoGetSize(NULL
, &height
);
506 else if ( height
== heightBest
)
508 // we don't need to manually manage our height, let the system use the
510 m_heightOwn
= wxDefaultCoord
;
512 else // non-default height specified
514 // set our new own height but be careful not to make it too big: the
515 // native control apparently stores it as a single byte and so setting
516 // own height to 256 pixels results in default height being used (255
518 m_heightOwn
= height
;
520 if ( m_heightOwn
> UCHAR_MAX
)
521 m_heightOwn
= UCHAR_MAX
;
522 // nor too small: see MSWUpdateVisibleHeight()
523 else if ( m_heightOwn
< COMBO_HEIGHT_ADJ
)
524 m_heightOwn
= COMBO_HEIGHT_ADJ
;
528 // the height which we must pass to Windows should be the total height of
529 // the control including the drop down list while the height given to us
530 // is, of course, just the height of the permanently visible part of it so
531 // add the drop down height to it
533 // don't make the drop down list too tall, arbitrarily limit it to 30
534 // items max and also don't make it too small if it's currently empty
535 size_t nItems
= GetCount();
536 if (!HasFlag(wxCB_SIMPLE
))
540 else if ( nItems
> 30 )
544 const int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, 0, 0);
545 int heightWithItems
= 0;
546 if (!HasFlag(wxCB_SIMPLE
))
547 heightWithItems
= height
+ hItem
*nItems
;
549 heightWithItems
= SetHeightSimpleComboBox(nItems
);
552 // do resize the native control
553 wxControl::DoSetSize(x
, y
, width
, heightWithItems
, sizeFlags
);
556 // make the control itself of the requested height: notice that this
557 // must be done after changing its size or it has no effect (apparently
558 // the height is reset to default during the control layout) and that it's
559 // useless to to do it when using the deferred sizing -- in this case it
560 // will be done from MSWEndDeferWindowPos()
561 #if wxUSE_DEFERRED_SIZING
562 if ( m_pendingSize
== wxDefaultSize
)
564 // not using deferred sizing, update it immediately
565 MSWUpdateVisibleHeight();
567 else // in the middle of deferred sizing
569 // we need to report the size of the visible part of the control back
570 // in GetSize() and not height stored by DoSetSize() in m_pendingSize
571 m_pendingSize
= wxSize(width
, height
);
573 #else // !wxUSE_DEFERRED_SIZING
574 // always update the visible height immediately
575 MSWUpdateVisibleHeight();
576 #endif // wxUSE_DEFERRED_SIZING
579 wxSize
wxChoice::DoGetBestSize() const
581 // find the widest string
584 const unsigned int nItems
= GetCount();
585 for ( unsigned int i
= 0; i
< nItems
; i
++ )
588 GetTextExtent(GetString(i
), &wLine
, NULL
);
589 if ( wLine
> wChoice
)
593 // give it some reasonable default value if there are no strings in the
598 // the combobox should be slightly larger than the widest string
599 wChoice
+= 5*GetCharWidth();
600 if( HasFlag( wxCB_SIMPLE
) )
602 hChoice
= SetHeightSimpleComboBox( nItems
);
605 hChoice
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(GetCharHeight());
607 wxSize
best(wChoice
, hChoice
);
612 int wxChoice::SetHeightSimpleComboBox(int nItems
) const
615 wxGetCharSize( GetHWND(), &cx
, &cy
, GetFont() );
616 int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, (WPARAM
)-1, 0);
617 return EDIT_HEIGHT_FROM_CHAR_HEIGHT( cy
) * wxMin( wxMax( nItems
, 3 ), 6 ) + hItem
- 1;
620 // ----------------------------------------------------------------------------
621 // MSW message handlers
622 // ----------------------------------------------------------------------------
624 WXLRESULT
wxChoice::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
630 int x
= (int)LOWORD(lParam
);
631 int y
= (int)HIWORD(lParam
);
633 // Ok, this is truly weird, but if a panel with a wxChoice
634 // loses the focus, then you get a *fake* WM_LBUTTONUP message
635 // with x = 65535 and y = 65535. Filter out this nonsense.
637 // VZ: I'd like to know how to reproduce this please...
638 if ( x
== 65535 && y
== 65535 )
643 // we have to handle both: one for the normal case and the other
645 case WM_CTLCOLOREDIT
:
646 case WM_CTLCOLORLISTBOX
:
647 case WM_CTLCOLORSTATIC
:
651 UnpackCtlColor(wParam
, lParam
, &hdc
, &hwnd
);
653 WXHBRUSH hbr
= MSWControlColor((WXHDC
)hdc
, hwnd
);
655 return (WXLRESULT
)hbr
;
656 //else: fall through to default window proc
660 return wxWindow::MSWWindowProc(nMsg
, wParam
, lParam
);
663 bool wxChoice::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
666 The native control provides a great variety in the events it sends in
667 the different selection scenarios (undoubtedly for greater amusement of
668 the programmers using it). For the reference, here are the cases when
669 the final selection is accepted (things are quite interesting when it
672 A. Selecting with just the arrows without opening the dropdown:
676 B. Opening dropdown with F4 and selecting with arrows:
678 2. many CBN_SELCHANGE while changing selection in the list
682 C. Selecting with the mouse:
684 -- no intermediate CBN_SELCHANGEs --
689 Admire the different order of messages in all of those cases, it must
690 surely have taken a lot of effort to Microsoft developers to achieve
696 // we use this value both because we don't want to track selection
697 // using CB_GETCURSEL while the dropdown is opened and because we
698 // need to reset the selection back to it if it's eventually
700 m_lastAcceptedSelection
= GetCurrentSelection();
704 // if the selection was accepted by the user, it should have been
705 // reset to wxID_NONE by CBN_SELENDOK, otherwise the selection was
706 // cancelled and we must restore the old one
707 if ( m_lastAcceptedSelection
!= wxID_NONE
)
709 SetSelection(m_lastAcceptedSelection
);
710 m_lastAcceptedSelection
= wxID_NONE
;
715 // reset it to prevent CBN_CLOSEUP from undoing the selection (it's
716 // ok to reset it now as GetCurrentSelection() will now return the
717 // same thing anyhow)
718 m_lastAcceptedSelection
= wxID_NONE
;
721 const int n
= GetSelection();
723 wxCommandEvent
event(wxEVT_COMMAND_CHOICE_SELECTED
, m_windowId
);
725 event
.SetEventObject(this);
729 event
.SetString(GetStringSelection());
730 InitCommandEventWithItems(event
, n
);
733 ProcessCommand(event
);
737 // don't handle CBN_SELENDCANCEL: just leave m_lastAcceptedSelection
738 // valid and the selection will be undone in CBN_CLOSEUP above
740 // don't handle CBN_SELCHANGE neither, we don't want to generate events
741 // while the dropdown is opened -- but do add it if we ever need this
750 WXHBRUSH
wxChoice::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
753 return MSWControlColorDisabled(hDC
);
755 return wxChoiceBase::MSWControlColor(hDC
, hWnd
);
758 #endif // wxUSE_CHOICE && !(__SMARTPHONE__ && __WXWINCE__)