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"
35 #include "wx/settings.h"
38 #include "wx/msw/private.h"
40 #if wxUSE_EXTENDED_RTTI
41 WX_DEFINE_FLAGS( wxChoiceStyle
)
43 wxBEGIN_FLAGS( wxChoiceStyle
)
44 // new style border flags, we put them first to
45 // use them for streaming out
46 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
47 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
48 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
49 wxFLAGS_MEMBER(wxBORDER_RAISED
)
50 wxFLAGS_MEMBER(wxBORDER_STATIC
)
51 wxFLAGS_MEMBER(wxBORDER_NONE
)
53 // old style border flags
54 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
55 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
56 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
57 wxFLAGS_MEMBER(wxRAISED_BORDER
)
58 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
59 wxFLAGS_MEMBER(wxBORDER
)
61 // standard window styles
62 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
63 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
64 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
65 wxFLAGS_MEMBER(wxWANTS_CHARS
)
66 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
67 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
68 wxFLAGS_MEMBER(wxVSCROLL
)
69 wxFLAGS_MEMBER(wxHSCROLL
)
71 wxEND_FLAGS( wxChoiceStyle
)
73 IMPLEMENT_DYNAMIC_CLASS_XTI(wxChoice
, wxControlWithItems
,"wx/choice.h")
75 wxBEGIN_PROPERTIES_TABLE(wxChoice
)
76 wxEVENT_PROPERTY( Select
, wxEVT_COMMAND_CHOICE_SELECTED
, wxCommandEvent
)
78 wxPROPERTY( Font
, wxFont
, SetFont
, GetFont
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
79 wxPROPERTY_COLLECTION( Choices
, wxArrayString
, wxString
, AppendString
, GetStrings
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
80 wxPROPERTY( Selection
,int, SetSelection
, GetSelection
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
81 wxPROPERTY_FLAGS( WindowStyle
, wxChoiceStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
82 wxEND_PROPERTIES_TABLE()
84 wxBEGIN_HANDLERS_TABLE(wxChoice
)
85 wxEND_HANDLERS_TABLE()
87 wxCONSTRUCTOR_4( wxChoice
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
)
89 IMPLEMENT_DYNAMIC_CLASS(wxChoice
, wxControlWithItems
)
98 // ============================================================================
100 // ============================================================================
102 // ----------------------------------------------------------------------------
104 // ----------------------------------------------------------------------------
106 bool wxChoice::Create(wxWindow
*parent
,
110 int n
, const wxString choices
[],
112 const wxValidator
& validator
,
113 const wxString
& name
)
115 // Experience shows that wxChoice vs. wxComboBox distinction confuses
116 // quite a few people - try to help them
117 wxASSERT_MSG( !(style
& wxCB_DROPDOWN
) &&
118 !(style
& wxCB_READONLY
) &&
119 !(style
& wxCB_SIMPLE
),
120 _T("this style flag is ignored by wxChoice, you ")
121 _T("probably want to use a wxComboBox") );
123 return CreateAndInit(parent
, id
, pos
, size
, n
, choices
, style
,
127 bool wxChoice::CreateAndInit(wxWindow
*parent
,
131 int n
, const wxString choices
[],
133 const wxValidator
& validator
,
134 const wxString
& name
)
136 // initialize wxControl
137 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
140 // now create the real HWND
141 if ( !MSWCreateControl(wxT("COMBOBOX"), wxEmptyString
, pos
, size
) )
145 // choice/combobox normally has "white" (depends on colour scheme, of
146 // course) background rather than inheriting the parent's background
147 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
149 // initialize the controls contents
150 for ( int i
= 0; i
< n
; i
++ )
155 // and now we may finally size the control properly (if needed)
156 SetInitialSize(size
);
161 void wxChoice::SetLabel(const wxString
& label
)
163 if ( FindString(label
) == wxNOT_FOUND
)
165 // unless we explicitly do this here, CB_GETCURSEL will continue to
166 // return the index of the previously selected item which will result
167 // in wrongly replacing the value being set now with the previously
168 // value if the user simply opens and closes (without selecting
169 // anything) the combobox popup
173 wxChoiceBase::SetLabel(label
);
176 bool wxChoice::Create(wxWindow
*parent
,
180 const wxArrayString
& choices
,
182 const wxValidator
& validator
,
183 const wxString
& name
)
185 wxCArrayString
chs(choices
);
186 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
187 style
, validator
, name
);
190 bool wxChoice::MSWShouldPreProcessMessage(WXMSG
*pMsg
)
192 MSG
*msg
= (MSG
*) pMsg
;
194 // if the dropdown list is visible, don't preprocess certain keys
195 if ( msg
->message
== WM_KEYDOWN
196 && (msg
->wParam
== VK_ESCAPE
|| msg
->wParam
== VK_RETURN
) )
198 if (::SendMessage(GetHwndOf(this), CB_GETDROPPEDSTATE
, 0, 0))
204 return wxControl::MSWShouldPreProcessMessage(pMsg
);
207 WXDWORD
wxChoice::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
209 // we never have an external border
210 WXDWORD msStyle
= wxControl::MSWGetStyle
212 (style
& ~wxBORDER_MASK
) | wxBORDER_NONE
, exstyle
215 // WS_CLIPSIBLINGS is useful with wxChoice and doesn't seem to result in
217 msStyle
|= WS_CLIPSIBLINGS
;
219 // wxChoice-specific styles
220 msStyle
|= CBS_DROPDOWNLIST
| WS_HSCROLL
| WS_VSCROLL
;
221 if ( style
& wxCB_SORT
)
227 wxChoice::~wxChoice()
232 // ----------------------------------------------------------------------------
233 // adding/deleting items to/from the list
234 // ----------------------------------------------------------------------------
236 int wxChoice::DoInsertItems(const wxArrayStringsAdapter
& items
,
238 void **clientData
, wxClientDataType type
)
240 MSWAllocStorage(items
, CB_INITSTORAGE
);
242 const bool append
= pos
== GetCount();
244 // use CB_ADDSTRING when appending at the end to make sure the control is
245 // resorted if it has wxCB_SORT style
246 const unsigned msg
= append
? CB_ADDSTRING
: CB_INSERTSTRING
;
252 const unsigned numItems
= items
.GetCount();
253 for ( unsigned i
= 0; i
< numItems
; ++i
)
255 n
= MSWInsertOrAppendItem(pos
, items
[i
], msg
);
256 if ( n
== wxNOT_FOUND
)
262 AssignNewItemClientData(n
, clientData
, i
, type
);
265 // we need to refresh our size in order to have enough space for the
268 MSWUpdateDropDownHeight();
270 InvalidateBestSize();
275 void wxChoice::DoDeleteOneItem(unsigned int n
)
277 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::Delete") );
279 SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
282 MSWUpdateDropDownHeight();
284 InvalidateBestSize();
287 void wxChoice::DoClear()
289 SendMessage(GetHwnd(), CB_RESETCONTENT
, 0, 0);
292 MSWUpdateDropDownHeight();
294 InvalidateBestSize();
297 // ----------------------------------------------------------------------------
299 // ----------------------------------------------------------------------------
301 int wxChoice::GetSelection() const
303 // if m_lastAcceptedSelection is set, it means that the dropdown is
304 // currently shown and that we want to use the last "permanent" selection
305 // instead of whatever is under the mouse pointer currently
307 // otherwise, get the selection from the control
308 return m_lastAcceptedSelection
== wxID_NONE
? GetCurrentSelection()
309 : m_lastAcceptedSelection
;
312 int wxChoice::GetCurrentSelection() const
314 return (int)SendMessage(GetHwnd(), CB_GETCURSEL
, 0, 0);
317 void wxChoice::SetSelection(int n
)
319 SendMessage(GetHwnd(), CB_SETCURSEL
, n
, 0);
322 // ----------------------------------------------------------------------------
323 // string list functions
324 // ----------------------------------------------------------------------------
326 unsigned int wxChoice::GetCount() const
328 return (unsigned int)SendMessage(GetHwnd(), CB_GETCOUNT
, 0, 0);
331 int wxChoice::FindString(const wxString
& s
, bool bCase
) const
333 #if defined(__WATCOMC__) && defined(__WIN386__)
334 // For some reason, Watcom in WIN386 mode crashes in the CB_FINDSTRINGEXACT message.
335 // wxChoice::Do it the long way instead.
336 unsigned int count
= GetCount();
337 for ( unsigned int i
= 0; i
< count
; i
++ )
339 // as CB_FINDSTRINGEXACT is case insensitive, be case insensitive too
340 if (GetString(i
).IsSameAs(s
, bCase
))
346 //TODO: Evidently some MSW versions (all?) don't like empty strings
347 //passed to SendMessage, so we have to do it ourselves in that case
350 unsigned int count
= GetCount();
351 for ( unsigned int i
= 0; i
< count
; i
++ )
353 if (GetString(i
).empty())
361 // back to base class search for not native search type
362 return wxItemContainerImmutable::FindString( s
, bCase
);
366 int pos
= (int)SendMessage(GetHwnd(), CB_FINDSTRINGEXACT
,
367 (WPARAM
)-1, (LPARAM
)s
.wx_str());
369 return pos
== LB_ERR
? wxNOT_FOUND
: pos
;
371 #endif // Watcom/!Watcom
374 void wxChoice::SetString(unsigned int n
, const wxString
& s
)
376 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::SetString") );
378 // we have to delete and add back the string as there is no way to change a
381 // we need to preserve the client data manually
382 void *oldData
= NULL
;
383 wxClientData
*oldObjData
= NULL
;
384 if ( HasClientUntypedData() )
385 oldData
= GetClientData(n
);
386 else if ( HasClientObjectData() )
387 oldObjData
= GetClientObject(n
);
389 ::SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
390 ::SendMessage(GetHwnd(), CB_INSERTSTRING
, n
, (LPARAM
)s
.wx_str() );
392 // restore the client data
394 SetClientData(n
, oldData
);
395 else if ( oldObjData
)
396 SetClientObject(n
, oldObjData
);
398 InvalidateBestSize();
401 wxString
wxChoice::GetString(unsigned int n
) const
403 int len
= (int)::SendMessage(GetHwnd(), CB_GETLBTEXTLEN
, n
, 0);
406 if ( len
!= CB_ERR
&& len
> 0 )
413 (LPARAM
)(wxChar
*)wxStringBuffer(str
, len
)
416 wxLogLastError(wxT("SendMessage(CB_GETLBTEXT)"));
423 // ----------------------------------------------------------------------------
425 // ----------------------------------------------------------------------------
427 void wxChoice::DoSetItemClientData(unsigned int n
, void* clientData
)
429 if ( ::SendMessage(GetHwnd(), CB_SETITEMDATA
,
430 n
, (LPARAM
)clientData
) == CB_ERR
)
432 wxLogLastError(wxT("CB_SETITEMDATA"));
436 void* wxChoice::DoGetItemClientData(unsigned int n
) const
438 LPARAM rc
= SendMessage(GetHwnd(), CB_GETITEMDATA
, n
, 0);
441 wxLogLastError(wxT("CB_GETITEMDATA"));
443 // unfortunately, there is no way to return an error code to the user
450 // ----------------------------------------------------------------------------
451 // wxMSW-specific geometry management
452 // ----------------------------------------------------------------------------
454 void wxChoice::MSWUpdateVisibleHeight()
456 if ( m_heightOwn
!= wxDefaultCoord
)
457 ::SendMessage(GetHwnd(), CB_SETITEMHEIGHT
, (WPARAM
)-1, m_heightOwn
);
460 #if wxUSE_DEFERRED_SIZING
461 void wxChoice::MSWEndDeferWindowPos()
463 // we can only set the height of the choice itself now as it is reset to
464 // default every time the control is resized
465 MSWUpdateVisibleHeight();
467 wxChoiceBase::MSWEndDeferWindowPos();
469 #endif // wxUSE_DEFERRED_SIZING
471 void wxChoice::MSWUpdateDropDownHeight()
473 // be careful to not change the width here
474 DoSetSize(wxDefaultCoord
, wxDefaultCoord
, wxDefaultCoord
, GetSize().y
,
475 wxSIZE_USE_EXISTING
);
478 void wxChoice::DoMoveWindow(int x
, int y
, int width
, int height
)
480 // here is why this is necessary: if the width is negative, the combobox
481 // window proc makes the window of the size width*height instead of
482 // interpreting height in the usual manner (meaning the height of the drop
483 // down list - usually the height specified in the call to MoveWindow()
484 // will not change the height of combo box per se)
486 // this behaviour is not documented anywhere, but this is just how it is
487 // here (NT 4.4) and, anyhow, the check shouldn't hurt - however without
488 // the check, constraints/sizers using combos may break the height
489 // constraint will have not at all the same value as expected
493 wxControl::DoMoveWindow(x
, y
, width
, height
);
496 void wxChoice::DoGetSize(int *w
, int *h
) const
498 // this is weird: sometimes, the height returned by Windows is clearly the
499 // total height of the control including the drop down list -- but only
500 // sometimes, and normally it isn't... I have no idea about what to do with
502 wxControl::DoGetSize(w
, h
);
505 void wxChoice::DoSetSize(int x
, int y
,
506 int width
, int height
,
509 const int heightOrig
= height
;
511 // the height which we must pass to Windows should be the total height of
512 // the control including the drop down list while the height given to us
513 // is, of course, just the height of the permanently visible part of it
514 if ( height
!= wxDefaultCoord
)
516 // set our new own height but be careful not to make it too big: the
517 // native control apparently stores it as a single byte and so setting
518 // own height to 256 pixels results in default height being used (255
520 if ( height
> UCHAR_MAX
)
522 m_heightOwn
= height
;
524 // don't make the drop down list too tall, arbitrarily limit it to 30
525 // items max and also don't make it too small if it's currently empty
526 size_t nItems
= GetCount();
529 else if ( nItems
> 30 )
532 // add space for the drop down list
533 const int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, 0, 0);
534 height
+= hItem
*(nItems
+ 1);
538 // We cannot pass wxDefaultCoord as height to wxControl. wxControl uses
539 // wxGetWindowRect() to determine the current height of the combobox,
540 // and then again sets the combobox's height to that value. Unfortunately,
541 // wxGetWindowRect doesn't include the dropdown list's height (at least
542 // on Win2K), so this would result in a combobox with dropdown height of
543 // 1 pixel. We have to determine the default height ourselves and call
544 // wxControl with that value instead.
548 if (::SendMessage(GetHwnd(), CB_GETDROPPEDCONTROLRECT
, 0, (LPARAM
) &r
) != 0)
550 height
= h
+ r
.bottom
- r
.top
;
554 wxControl::DoSetSize(x
, y
, width
, height
, 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
, heightOrig
);
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
583 const unsigned int nItems
= GetCount();
584 for ( unsigned int i
= 0; i
< nItems
; i
++ )
587 GetTextExtent(GetString(i
), &wLine
, NULL
);
588 if ( wLine
> wChoice
)
592 // give it some reasonable default value if there are no strings in the
597 // the combobox should be slightly larger than the widest string
598 wChoice
+= 5*GetCharWidth();
600 wxSize
best(wChoice
, EDIT_HEIGHT_FROM_CHAR_HEIGHT(GetCharHeight()));
605 // ----------------------------------------------------------------------------
606 // MSW message handlers
607 // ----------------------------------------------------------------------------
609 WXLRESULT
wxChoice::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
615 int x
= (int)LOWORD(lParam
);
616 int y
= (int)HIWORD(lParam
);
618 // Ok, this is truly weird, but if a panel with a wxChoice
619 // loses the focus, then you get a *fake* WM_LBUTTONUP message
620 // with x = 65535 and y = 65535. Filter out this nonsense.
622 // VZ: I'd like to know how to reproduce this please...
623 if ( x
== 65535 && y
== 65535 )
628 // we have to handle both: one for the normal case and the other
630 case WM_CTLCOLOREDIT
:
631 case WM_CTLCOLORLISTBOX
:
632 case WM_CTLCOLORSTATIC
:
636 UnpackCtlColor(wParam
, lParam
, &hdc
, &hwnd
);
638 WXHBRUSH hbr
= MSWControlColor((WXHDC
)hdc
, hwnd
);
640 return (WXLRESULT
)hbr
;
641 //else: fall through to default window proc
645 return wxWindow::MSWWindowProc(nMsg
, wParam
, lParam
);
648 bool wxChoice::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
651 The native control provides a great variety in the events it sends in
652 the different selection scenarios (undoubtedly for greater amusement of
653 the programmers using it). For the reference, here are the cases when
654 the final selection is accepted (things are quite interesting when it
657 A. Selecting with just the arrows without opening the dropdown:
661 B. Opening dropdown with F4 and selecting with arrows:
663 2. many CBN_SELCHANGE while changing selection in the list
667 C. Selecting with the mouse:
669 -- no intermediate CBN_SELCHANGEs --
674 Admire the different order of messages in all of those cases, it must
675 surely have taken a lot of effort to Microsoft developers to achieve
681 // we use this value both because we don't want to track selection
682 // using CB_GETCURSEL while the dropdown is opened and because we
683 // need to reset the selection back to it if it's eventually
685 m_lastAcceptedSelection
= GetCurrentSelection();
689 // if the selection was accepted by the user, it should have been
690 // reset to wxID_NONE by CBN_SELENDOK, otherwise the selection was
691 // cancelled and we must restore the old one
692 if ( m_lastAcceptedSelection
!= wxID_NONE
)
694 SetSelection(m_lastAcceptedSelection
);
695 m_lastAcceptedSelection
= wxID_NONE
;
700 // reset it to prevent CBN_CLOSEUP from undoing the selection (it's
701 // ok to reset it now as GetCurrentSelection() will now return the
702 // same thing anyhow)
703 m_lastAcceptedSelection
= wxID_NONE
;
706 const int n
= GetSelection();
708 wxCommandEvent
event(wxEVT_COMMAND_CHOICE_SELECTED
, m_windowId
);
710 event
.SetEventObject(this);
714 event
.SetString(GetStringSelection());
715 InitCommandEventWithItems(event
, n
);
718 ProcessCommand(event
);
722 // don't handle CBN_SELENDCANCEL: just leave m_lastAcceptedSelection
723 // valid and the selection will be undone in CBN_CLOSEUP above
725 // don't handle CBN_SELCHANGE neither, we don't want to generate events
726 // while the dropdown is opened -- but do add it if we ever need this
735 WXHBRUSH
wxChoice::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
738 return MSWControlColorDisabled(hDC
);
740 return wxChoiceBase::MSWControlColor(hDC
, hWnd
);
743 #endif // wxUSE_CHOICE && !(__SMARTPHONE__ && __WXWINCE__)