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 bool wxChoice::Create(wxWindow
*parent
,
165 const wxArrayString
& choices
,
167 const wxValidator
& validator
,
168 const wxString
& name
)
170 wxCArrayString
chs(choices
);
171 return Create(parent
, id
, pos
, size
, chs
.GetCount(), chs
.GetStrings(),
172 style
, validator
, name
);
175 bool wxChoice::MSWShouldPreProcessMessage(WXMSG
*pMsg
)
177 MSG
*msg
= (MSG
*) pMsg
;
179 // if the dropdown list is visible, don't preprocess certain keys
180 if ( msg
->message
== WM_KEYDOWN
181 && (msg
->wParam
== VK_ESCAPE
|| msg
->wParam
== VK_RETURN
) )
183 if (::SendMessage(GetHwndOf(this), CB_GETDROPPEDSTATE
, 0, 0))
189 return wxControl::MSWShouldPreProcessMessage(pMsg
);
192 WXDWORD
wxChoice::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
194 // we never have an external border
195 WXDWORD msStyle
= wxControl::MSWGetStyle
197 (style
& ~wxBORDER_MASK
) | wxBORDER_NONE
, exstyle
200 // WS_CLIPSIBLINGS is useful with wxChoice and doesn't seem to result in
202 msStyle
|= WS_CLIPSIBLINGS
;
204 // wxChoice-specific styles
205 msStyle
|= CBS_DROPDOWNLIST
| WS_HSCROLL
| WS_VSCROLL
;
206 if ( style
& wxCB_SORT
)
212 wxChoice::~wxChoice()
217 // ----------------------------------------------------------------------------
218 // adding/deleting items to/from the list
219 // ----------------------------------------------------------------------------
221 int wxChoice::DoAppend(const wxString
& item
)
223 int n
= (int)SendMessage(GetHwnd(), CB_ADDSTRING
, 0,
224 (LPARAM
)item
.wx_str());
227 wxLogLastError(wxT("SendMessage(CB_ADDSTRING)"));
231 // we need to refresh our size in order to have enough space for the
234 UpdateVisibleHeight();
237 InvalidateBestSize();
241 int wxChoice::DoInsert(const wxString
& item
, unsigned int pos
)
243 wxCHECK_MSG(!(GetWindowStyle() & wxCB_SORT
), -1, wxT("can't insert into sorted list"));
244 wxCHECK_MSG(IsValidInsert(pos
), -1, wxT("invalid index"));
246 int n
= (int)SendMessage(GetHwnd(), CB_INSERTSTRING
, pos
,
247 (LPARAM
)item
.wx_str());
250 wxLogLastError(wxT("SendMessage(CB_INSERTSTRING)"));
255 UpdateVisibleHeight();
258 InvalidateBestSize();
262 void wxChoice::Delete(unsigned int n
)
264 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::Delete") );
266 if ( HasClientObjectData() )
268 delete GetClientObject(n
);
271 SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
274 UpdateVisibleHeight();
276 InvalidateBestSize();
279 void wxChoice::Clear()
283 SendMessage(GetHwnd(), CB_RESETCONTENT
, 0, 0);
286 UpdateVisibleHeight();
288 InvalidateBestSize();
291 void wxChoice::Free()
293 if ( HasClientObjectData() )
295 unsigned int count
= GetCount();
296 for ( unsigned int n
= 0; n
< count
; n
++ )
298 delete GetClientObject(n
);
303 // ----------------------------------------------------------------------------
305 // ----------------------------------------------------------------------------
307 int wxChoice::GetSelection() const
309 // if m_lastAcceptedSelection is set, it means that the dropdown is
310 // currently shown and that we want to use the last "permanent" selection
311 // instead of whatever is under the mouse pointer currently
313 // otherwise, get the selection from the control
314 return m_lastAcceptedSelection
== wxID_NONE
? GetCurrentSelection()
315 : m_lastAcceptedSelection
;
318 int wxChoice::GetCurrentSelection() const
320 return (int)SendMessage(GetHwnd(), CB_GETCURSEL
, 0, 0);
323 void wxChoice::SetSelection(int n
)
325 SendMessage(GetHwnd(), CB_SETCURSEL
, n
, 0);
328 // ----------------------------------------------------------------------------
329 // string list functions
330 // ----------------------------------------------------------------------------
332 unsigned int wxChoice::GetCount() const
334 return (unsigned int)SendMessage(GetHwnd(), CB_GETCOUNT
, 0, 0);
337 int wxChoice::FindString(const wxString
& s
, bool bCase
) const
339 #if defined(__WATCOMC__) && defined(__WIN386__)
340 // For some reason, Watcom in WIN386 mode crashes in the CB_FINDSTRINGEXACT message.
341 // wxChoice::Do it the long way instead.
342 unsigned int count
= GetCount();
343 for ( unsigned int i
= 0; i
< count
; i
++ )
345 // as CB_FINDSTRINGEXACT is case insensitive, be case insensitive too
346 if (GetString(i
).IsSameAs(s
, bCase
))
352 //TODO: Evidently some MSW versions (all?) don't like empty strings
353 //passed to SendMessage, so we have to do it ourselves in that case
356 unsigned int count
= GetCount();
357 for ( unsigned int i
= 0; i
< count
; i
++ )
359 if (GetString(i
).empty())
367 // back to base class search for not native search type
368 return wxItemContainerImmutable::FindString( s
, bCase
);
372 int pos
= (int)SendMessage(GetHwnd(), CB_FINDSTRINGEXACT
,
373 (WPARAM
)-1, (LPARAM
)s
.wx_str());
375 return pos
== LB_ERR
? wxNOT_FOUND
: pos
;
377 #endif // Watcom/!Watcom
380 void wxChoice::SetString(unsigned int n
, const wxString
& s
)
382 wxCHECK_RET( IsValid(n
), wxT("invalid item index in wxChoice::SetString") );
384 // we have to delete and add back the string as there is no way to change a
387 // we need to preserve the client data
389 if ( m_clientDataItemsType
!= wxClientData_None
)
391 data
= DoGetItemClientData(n
);
393 else // no client data
398 ::SendMessage(GetHwnd(), CB_DELETESTRING
, n
, 0);
399 ::SendMessage(GetHwnd(), CB_INSERTSTRING
, n
, (LPARAM
)s
.wx_str() );
403 DoSetItemClientData(n
, data
);
405 //else: it's already NULL by default
407 InvalidateBestSize();
410 wxString
wxChoice::GetString(unsigned int n
) const
412 int len
= (int)::SendMessage(GetHwnd(), CB_GETLBTEXTLEN
, n
, 0);
415 if ( len
!= CB_ERR
&& len
> 0 )
422 (LPARAM
)(wxChar
*)wxStringBuffer(str
, len
)
425 wxLogLastError(wxT("SendMessage(CB_GETLBTEXT)"));
432 // ----------------------------------------------------------------------------
434 // ----------------------------------------------------------------------------
436 void wxChoice::DoSetItemClientData(unsigned int n
, void* clientData
)
438 if ( ::SendMessage(GetHwnd(), CB_SETITEMDATA
,
439 n
, (LPARAM
)clientData
) == CB_ERR
)
441 wxLogLastError(wxT("CB_SETITEMDATA"));
445 void* wxChoice::DoGetItemClientData(unsigned int n
) const
447 LPARAM rc
= SendMessage(GetHwnd(), CB_GETITEMDATA
, n
, 0);
450 wxLogLastError(wxT("CB_GETITEMDATA"));
452 // unfortunately, there is no way to return an error code to the user
459 void wxChoice::DoSetItemClientObject(unsigned int n
, wxClientData
* clientData
)
461 DoSetItemClientData(n
, clientData
);
464 wxClientData
* wxChoice::DoGetItemClientObject(unsigned int n
) const
466 return (wxClientData
*)DoGetItemClientData(n
);
469 // ----------------------------------------------------------------------------
470 // wxMSW specific helpers
471 // ----------------------------------------------------------------------------
473 void wxChoice::UpdateVisibleHeight()
475 // be careful to not change the width here
476 DoSetSize(wxDefaultCoord
, wxDefaultCoord
, wxDefaultCoord
, GetSize().y
, wxSIZE_USE_EXISTING
);
479 void wxChoice::DoMoveWindow(int x
, int y
, int width
, int height
)
481 // here is why this is necessary: if the width is negative, the combobox
482 // window proc makes the window of the size width*height instead of
483 // interpreting height in the usual manner (meaning the height of the drop
484 // down list - usually the height specified in the call to MoveWindow()
485 // will not change the height of combo box per se)
487 // this behaviour is not documented anywhere, but this is just how it is
488 // here (NT 4.4) and, anyhow, the check shouldn't hurt - however without
489 // the check, constraints/sizers using combos may break the height
490 // constraint will have not at all the same value as expected
494 wxControl::DoMoveWindow(x
, y
, width
, height
);
497 void wxChoice::DoGetSize(int *w
, int *h
) const
499 // this is weird: sometimes, the height returned by Windows is clearly the
500 // total height of the control including the drop down list -- but only
501 // sometimes, and normally it isn't... I have no idea about what to do with
503 wxControl::DoGetSize(w
, h
);
506 void wxChoice::DoSetSize(int x
, int y
,
507 int width
, int height
,
510 int heightOrig
= height
;
512 // the height which we must pass to Windows should be the total height of
513 // the control including the drop down list while the height given to us
514 // is, of course, just the height of the permanently visible part of it
515 if ( height
!= wxDefaultCoord
)
517 // don't make the drop down list too tall, arbitrarily limit it to 40
518 // items max and also don't leave it empty
519 size_t nItems
= GetCount();
522 else if ( nItems
> 24 )
525 // add space for the drop down list
526 const int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, 0, 0);
527 height
+= hItem
*(nItems
+ 1);
531 // We cannot pass wxDefaultCoord as height to wxControl. wxControl uses
532 // wxGetWindowRect() to determine the current height of the combobox,
533 // and then again sets the combobox's height to that value. Unfortunately,
534 // wxGetWindowRect doesn't include the dropdown list's height (at least
535 // on Win2K), so this would result in a combobox with dropdown height of
536 // 1 pixel. We have to determine the default height ourselves and call
537 // wxControl with that value instead.
541 if (::SendMessage(GetHwnd(), CB_GETDROPPEDCONTROLRECT
, 0, (LPARAM
) &r
) != 0)
543 height
= h
+ r
.bottom
- r
.top
;
547 wxControl::DoSetSize(x
, y
, width
, height
, sizeFlags
);
549 // If we're storing a pending size, make sure we store
550 // the original size for reporting back to the app.
551 if (m_pendingSize
!= wxDefaultSize
)
552 m_pendingSize
= wxSize(width
, heightOrig
);
554 // This solution works on XP, but causes choice/combobox lists to be
555 // too short on W2K and earlier.
557 int widthCurrent
, heightCurrent
;
558 DoGetSize(&widthCurrent
, &heightCurrent
);
560 // the height which we must pass to Windows should be the total height of
561 // the control including the drop down list while the height given to us
562 // is, of course, just the height of the permanently visible part of it
563 if ( height
!= wxDefaultCoord
&& height
!= heightCurrent
)
565 // don't make the drop down list too tall, arbitrarily limit it to 40
566 // items max and also don't leave it empty
567 unsigned int nItems
= GetCount();
570 else if ( nItems
> 24 )
573 // add space for the drop down list
574 const int hItem
= SendMessage(GetHwnd(), CB_GETITEMHEIGHT
, 0, 0);
575 height
+= hItem
*(nItems
+ 1);
577 else // keep the same height as now
579 // normally wxWindow::DoSetSize() checks if we set the same size as the
580 // window already has and does nothing in this case, but for us the
581 // check fails as the size we pass to it includes the dropdown while
582 // the size returned by our GetSize() does not, so test if the size
583 // didn't really change ourselves here
584 if ( width
== wxDefaultCoord
|| width
== widthCurrent
)
586 // size doesn't change, what about position?
587 int xCurrent
, yCurrent
;
588 DoGetPosition(&xCurrent
, &yCurrent
);
589 const bool defMeansUnchanged
= !(sizeFlags
& wxSIZE_ALLOW_MINUS_ONE
);
590 if ( ((x
== wxDefaultCoord
&& defMeansUnchanged
) || x
== xCurrent
)
592 ((y
== wxDefaultCoord
&& defMeansUnchanged
) || y
== yCurrent
) )
594 // nothing changes, nothing to do
599 // We cannot pass wxDefaultCoord as height to wxControl. wxControl uses
600 // wxGetWindowRect() to determine the current height of the combobox,
601 // and then again sets the combobox's height to that value. Unfortunately,
602 // wxGetWindowRect doesn't include the dropdown list's height (at least
603 // on Win2K), so this would result in a combobox with dropdown height of
604 // 1 pixel. We have to determine the default height ourselves and call
605 // wxControl with that value instead.
607 // Also notice that sometimes CB_GETDROPPEDCONTROLRECT seems to return
608 // wildly incorrect values (~32000) which looks like a bug in it, just
609 // ignore them in this case
611 if ( ::SendMessage(GetHwnd(), CB_GETDROPPEDCONTROLRECT
, 0, (LPARAM
) &r
)
612 && r
.bottom
< 30000 )
614 height
= heightCurrent
+ r
.bottom
- r
.top
;
618 wxControl::DoSetSize(x
, y
, width
, height
, sizeFlags
);
622 wxSize
wxChoice::DoGetBestSize() const
624 // find the widest string
626 const unsigned int nItems
= GetCount();
627 for ( unsigned int i
= 0; i
< nItems
; i
++ )
630 GetTextExtent(GetString(i
), &wLine
, NULL
);
631 if ( wLine
> wChoice
)
635 // give it some reasonable default value if there are no strings in the
640 // the combobox should be slightly larger than the widest string
641 wChoice
+= 5*GetCharWidth();
643 wxSize
best(wChoice
, EDIT_HEIGHT_FROM_CHAR_HEIGHT(GetCharHeight()));
648 WXLRESULT
wxChoice::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
654 int x
= (int)LOWORD(lParam
);
655 int y
= (int)HIWORD(lParam
);
657 // Ok, this is truly weird, but if a panel with a wxChoice
658 // loses the focus, then you get a *fake* WM_LBUTTONUP message
659 // with x = 65535 and y = 65535. Filter out this nonsense.
661 // VZ: I'd like to know how to reproduce this please...
662 if ( x
== 65535 && y
== 65535 )
667 // we have to handle both: one for the normal case and the other
669 case WM_CTLCOLOREDIT
:
670 case WM_CTLCOLORLISTBOX
:
671 case WM_CTLCOLORSTATIC
:
675 UnpackCtlColor(wParam
, lParam
, &hdc
, &hwnd
);
677 WXHBRUSH hbr
= MSWControlColor((WXHDC
)hdc
, hwnd
);
679 return (WXLRESULT
)hbr
;
680 //else: fall through to default window proc
684 return wxWindow::MSWWindowProc(nMsg
, wParam
, lParam
);
687 bool wxChoice::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
690 The native control provides a great variety in the events it sends in
691 the different selection scenarios (undoubtedly for greater amusement of
692 the programmers using it). For the reference, here are the cases when
693 the final selection is accepted (things are quite interesting when it
696 A. Selecting with just the arrows without opening the dropdown:
700 B. Opening dropdown with F4 and selecting with arrows:
702 2. many CBN_SELCHANGE while changing selection in the list
706 C. Selecting with the mouse:
708 -- no intermediate CBN_SELCHANGEs --
713 Admire the different order of messages in all of those cases, it must
714 surely have taken a lot of effort to Microsoft developers to achieve
720 // we use this value both because we don't want to track selection
721 // using CB_GETCURSEL while the dropdown is opened and because we
722 // need to reset the selection back to it if it's eventually
724 m_lastAcceptedSelection
= GetCurrentSelection();
725 if ( m_lastAcceptedSelection
== -1 )
727 // no current selection so no need to restore it later (this
728 // happens when opening a combobox containing text not from its
729 // list of items and we shouldn't erase this text)
730 m_lastAcceptedSelection
= wxID_NONE
;
735 // if the selection was accepted by the user, it should have been
736 // reset to wxID_NONE by CBN_SELENDOK, otherwise the selection was
737 // cancelled and we must restore the old one
738 if ( m_lastAcceptedSelection
!= wxID_NONE
)
740 SetSelection(m_lastAcceptedSelection
);
741 m_lastAcceptedSelection
= wxID_NONE
;
746 // reset it to prevent CBN_CLOSEUP from undoing the selection (it's
747 // ok to reset it now as GetCurrentSelection() will now return the
748 // same thing anyhow)
749 m_lastAcceptedSelection
= wxID_NONE
;
752 const int n
= GetSelection();
754 wxCommandEvent
event(wxEVT_COMMAND_CHOICE_SELECTED
, m_windowId
);
756 event
.SetEventObject(this);
760 event
.SetString(GetStringSelection());
761 InitCommandEventWithItems(event
, n
);
764 ProcessCommand(event
);
768 // don't handle CBN_SELENDCANCEL: just leave m_lastAcceptedSelection
769 // valid and the selection will be undone in CBN_CLOSEUP above
771 // don't handle CBN_SELCHANGE neither, we don't want to generate events
772 // while the dropdown is opened -- but do add it if we ever need this
781 WXHBRUSH
wxChoice::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
784 return MSWControlColorDisabled(hDC
);
786 return wxChoiceBase::MSWControlColor(hDC
, hWnd
);
789 #endif // wxUSE_CHOICE && !(__SMARTPHONE__ && __WXWINCE__)