Fix generation of wxEVT_CHAR in wxMSW wxComboBox.
[wxWidgets.git] / src / msw / combobox.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/combobox.cpp
3 // Purpose: wxComboBox class
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 01/02/97
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_COMBOBOX
28
29 #include "wx/combobox.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/settings.h"
34 #include "wx/log.h"
35 // for wxEVT_COMMAND_TEXT_ENTER
36 #include "wx/textctrl.h"
37 #include "wx/app.h"
38 #include "wx/brush.h"
39 #endif
40
41 #include "wx/clipbrd.h"
42 #include "wx/dynlib.h"
43 #include "wx/wupdlock.h"
44 #include "wx/msw/private.h"
45
46 #if wxUSE_UXTHEME
47 #include "wx/msw/uxtheme.h"
48 #endif
49
50 #if wxUSE_TOOLTIPS
51 #include "wx/tooltip.h"
52 #endif // wxUSE_TOOLTIPS
53
54 // ----------------------------------------------------------------------------
55 // wxWin macros
56 // ----------------------------------------------------------------------------
57
58 BEGIN_EVENT_TABLE(wxComboBox, wxControl)
59 EVT_MENU(wxID_CUT, wxComboBox::OnCut)
60 EVT_MENU(wxID_COPY, wxComboBox::OnCopy)
61 EVT_MENU(wxID_PASTE, wxComboBox::OnPaste)
62 EVT_MENU(wxID_UNDO, wxComboBox::OnUndo)
63 EVT_MENU(wxID_REDO, wxComboBox::OnRedo)
64 EVT_MENU(wxID_CLEAR, wxComboBox::OnDelete)
65 EVT_MENU(wxID_SELECTALL, wxComboBox::OnSelectAll)
66
67 EVT_UPDATE_UI(wxID_CUT, wxComboBox::OnUpdateCut)
68 EVT_UPDATE_UI(wxID_COPY, wxComboBox::OnUpdateCopy)
69 EVT_UPDATE_UI(wxID_PASTE, wxComboBox::OnUpdatePaste)
70 EVT_UPDATE_UI(wxID_UNDO, wxComboBox::OnUpdateUndo)
71 EVT_UPDATE_UI(wxID_REDO, wxComboBox::OnUpdateRedo)
72 EVT_UPDATE_UI(wxID_CLEAR, wxComboBox::OnUpdateDelete)
73 EVT_UPDATE_UI(wxID_SELECTALL, wxComboBox::OnUpdateSelectAll)
74 END_EVENT_TABLE()
75
76 // ----------------------------------------------------------------------------
77 // function prototypes
78 // ----------------------------------------------------------------------------
79
80 LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
81 UINT message,
82 WPARAM wParam,
83 LPARAM lParam);
84
85 // ---------------------------------------------------------------------------
86 // global vars
87 // ---------------------------------------------------------------------------
88
89 // the pointer to standard radio button wnd proc
90 static WNDPROC gs_wndprocEdit = (WNDPROC)NULL;
91
92 // ============================================================================
93 // implementation
94 // ============================================================================
95
96 // ----------------------------------------------------------------------------
97 // wnd proc for subclassed edit control
98 // ----------------------------------------------------------------------------
99
100 LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
101 UINT message,
102 WPARAM wParam,
103 LPARAM lParam)
104 {
105 HWND hwndCombo = ::GetParent(hWnd);
106 wxWindow *win = wxFindWinFromHandle((WXHWND)hwndCombo);
107
108 switch ( message )
109 {
110 // forward some messages to the combobox to generate the appropriate
111 // wxEvents from them
112 case WM_KEYUP:
113 case WM_KEYDOWN:
114 case WM_CHAR:
115 case WM_SYSCHAR:
116 case WM_SYSKEYDOWN:
117 case WM_SYSKEYUP:
118 case WM_SETFOCUS:
119 case WM_KILLFOCUS:
120 {
121 wxComboBox *combo = wxDynamicCast(win, wxComboBox);
122 if ( !combo )
123 {
124 // we can get WM_KILLFOCUS while our parent is already half
125 // destroyed and hence doesn't look like a combobx any
126 // longer, check for it to avoid bogus assert failures
127 if ( !win->IsBeingDeleted() )
128 {
129 wxFAIL_MSG( wxT("should have combo as parent") );
130 }
131 }
132 else if ( combo->MSWProcessEditMsg(message, wParam, lParam) )
133 {
134 // handled by parent
135 return 0;
136 }
137 }
138 break;
139
140 case WM_GETDLGCODE:
141 {
142 wxCHECK_MSG( win, 0, wxT("should have a parent") );
143
144 if ( win->GetWindowStyle() & wxTE_PROCESS_ENTER )
145 {
146 // need to return a custom dlg code or we'll never get it
147 return DLGC_WANTMESSAGE;
148 }
149 }
150 break;
151 }
152
153 return ::CallWindowProc(CASTWNDPROC gs_wndprocEdit, hWnd, message, wParam, lParam);
154 }
155
156 // ----------------------------------------------------------------------------
157 // wxComboBox callbacks
158 // ----------------------------------------------------------------------------
159
160 WXLRESULT wxComboBox::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
161 {
162 // TODO: handle WM_CTLCOLOR messages from our EDIT control to be able to
163 // set its colour correctly (to be the same as our own one)
164
165 switch ( nMsg )
166 {
167 case WM_SIZE:
168 // wxStaticBox can generate this message, when modifying the control's style.
169 // This causes the content of the combobox to be selected, for some reason.
170 case WM_STYLECHANGED:
171 {
172 // combobox selection sometimes spontaneously changes when its
173 // size changes, restore it to the old value if necessary
174 if ( !GetEditHWNDIfAvailable() )
175 break;
176
177 long fromOld, toOld;
178 GetSelection(&fromOld, &toOld);
179
180 // if an editable combobox has a not empty text not from the
181 // list, it tries to autocomplete it from the list when it is
182 // resized, but we don't want this to happen as it doesn't seem
183 // to make any sense, so we forcefully restore the old text
184 wxString textOld;
185 if ( !HasFlag(wxCB_READONLY) && GetCurrentSelection() == -1 )
186 textOld = GetValue();
187
188 // eliminate flickering during following hacks
189 wxWindowUpdateLocker lock(this);
190
191 WXLRESULT result = wxChoice::MSWWindowProc(nMsg, wParam, lParam);
192
193 if ( !textOld.empty() && GetValue() != textOld )
194 SetLabel(textOld);
195
196 long fromNew, toNew;
197 GetSelection(&fromNew, &toNew);
198
199 if ( fromOld != fromNew || toOld != toNew )
200 {
201 SetSelection(fromOld, toOld);
202 }
203
204 return result;
205 }
206 }
207
208 return wxChoice::MSWWindowProc(nMsg, wParam, lParam);
209 }
210
211 bool wxComboBox::MSWProcessEditMsg(WXUINT msg, WXWPARAM wParam, WXLPARAM lParam)
212 {
213 switch ( msg )
214 {
215 case WM_CHAR:
216 // for compatibility with wxTextCtrl, generate a special message
217 // when Enter is pressed
218 if ( wParam == VK_RETURN )
219 {
220 if (SendMessage(GetHwnd(), CB_GETDROPPEDSTATE, 0, 0))
221 return false;
222
223 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
224
225 const int sel = GetSelection();
226 event.SetInt(sel);
227 event.SetString(GetValue());
228 InitCommandEventWithItems(event, sel);
229
230 if ( ProcessCommand(event) )
231 {
232 // don't let the event through to the native control
233 // because it doesn't need it and may generate an annoying
234 // beep if it gets it
235 return true;
236 }
237 }
238 // fall through
239
240 case WM_SYSCHAR:
241 case WM_SYSKEYDOWN:
242 case WM_KEYDOWN:
243 case WM_SYSKEYUP:
244 case WM_KEYUP:
245 case WM_SETFOCUS:
246 case WM_KILLFOCUS:
247 case WM_CUT:
248 case WM_COPY:
249 case WM_PASTE:
250 // For the messages above the result is not used.
251 WXLRESULT result;
252 return MSWHandleMessage(&result, msg, wParam, lParam);
253 }
254
255 return false;
256 }
257
258 bool wxComboBox::MSWCommand(WXUINT param, WXWORD id)
259 {
260 int sel = -1;
261 wxString value;
262
263 switch ( param )
264 {
265 case CBN_DROPDOWN:
266 // remember the last selection, just as wxChoice does
267 m_lastAcceptedSelection = GetCurrentSelection();
268 if ( m_lastAcceptedSelection == -1 )
269 {
270 // but unlike with wxChoice we may have no selection but still
271 // have some text and we should avoid erasing it if the drop
272 // down is cancelled (see #8474)
273 m_lastAcceptedSelection = wxID_NONE;
274 }
275 {
276 wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_DROPDOWN, GetId());
277 event.SetEventObject(this);
278 ProcessCommand(event);
279 }
280 break;
281 case CBN_CLOSEUP:
282 {
283 wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_CLOSEUP, GetId());
284 event.SetEventObject(this);
285 ProcessCommand(event);
286 }
287 break;
288 case CBN_SELENDOK:
289 #ifndef __SMARTPHONE__
290 // we need to reset this to prevent the selection from being undone
291 // by wxChoice, see wxChoice::MSWCommand() and comments there
292 m_lastAcceptedSelection = wxID_NONE;
293 #endif
294
295 // set these variables so that they could be also fixed in
296 // CBN_EDITCHANGE below
297 sel = GetSelection();
298 value = GetStringSelection();
299
300 // this string is going to become the new combobox value soon but
301 // we need it to be done right now, otherwise the event handler
302 // could get a wrong value when it calls our GetValue()
303 ::SetWindowText(GetHwnd(), value.t_str());
304
305 {
306 wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_SELECTED, GetId());
307 event.SetInt(sel);
308 event.SetString(value);
309 InitCommandEventWithItems(event, sel);
310
311 ProcessCommand(event);
312 }
313
314 // fall through: for compability with wxGTK, also send the text
315 // update event when the selection changes (this also seems more
316 // logical as the text does change)
317
318 case CBN_EDITCHANGE:
319 if ( m_allowTextEvents )
320 {
321 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId());
322
323 // if sel != -1, value was already initialized above
324 if ( sel == -1 )
325 {
326 value = wxGetWindowText(GetHwnd());
327 }
328
329 event.SetString(value);
330 InitCommandEventWithItems(event, sel);
331
332 ProcessCommand(event);
333 }
334 break;
335
336 default:
337 return wxChoice::MSWCommand(param, id);
338 }
339
340 // skip wxChoice version as it would generate its own events for
341 // CBN_SELENDOK and also interfere with our handling of CBN_DROPDOWN
342 return true;
343 }
344
345 bool wxComboBox::MSWShouldPreProcessMessage(WXMSG *pMsg)
346 {
347 // prevent command accelerators from stealing editing
348 // hotkeys when we have the focus
349 if (wxIsCtrlDown())
350 {
351 WPARAM vkey = pMsg->wParam;
352
353 switch (vkey)
354 {
355 case 'C':
356 case 'V':
357 case 'X':
358 case VK_INSERT:
359 case VK_DELETE:
360 case VK_HOME:
361 case VK_END:
362 return false;
363 }
364 }
365
366 return wxChoice::MSWShouldPreProcessMessage(pMsg);
367 }
368
369 WXHWND wxComboBox::GetEditHWNDIfAvailable() const
370 {
371 #if wxUSE_DYNLIB_CLASS
372 #if defined(WINVER) && WINVER >= 0x0500
373 typedef BOOL (WINAPI *GetComboBoxInfo_t)(HWND, COMBOBOXINFO*);
374 static GetComboBoxInfo_t s_pfnGetComboBoxInfo = NULL;
375 static bool s_triedToLoad = false;
376 if ( !s_triedToLoad )
377 {
378 s_triedToLoad = true;
379 wxLoadedDLL dllUser32("user32.dll");
380 wxDL_INIT_FUNC(s_pfn, GetComboBoxInfo, dllUser32);
381 }
382
383 if ( s_pfnGetComboBoxInfo )
384 {
385 WinStruct<COMBOBOXINFO> info;
386 (*s_pfnGetComboBoxInfo)(GetHwnd(), &info);
387 return info.hwndItem;
388 }
389 #endif // WINVER >= 0x0500
390 #endif // wxUSE_DYNLIB_CLASS
391
392 if (HasFlag(wxCB_SIMPLE))
393 {
394 POINT pt;
395 pt.x = pt.y = 4;
396 return (WXHWND) ::ChildWindowFromPoint(GetHwnd(), pt);
397 }
398
399 // notice that a slightly safer alternative could be to use FindWindowEx()
400 // but it's not available under WinCE so just take the first child for now
401 // to keep one version of the code for all platforms and fix it later if
402 // problems are discovered
403
404 // we assume that the only child of the combobox is the edit window
405 return (WXHWND)::GetWindow(GetHwnd(), GW_CHILD);
406 }
407
408 WXHWND wxComboBox::GetEditHWND() const
409 {
410 // this function should not be called for wxCB_READONLY controls, it is
411 // the callers responsibility to check this
412 wxASSERT_MSG( !HasFlag(wxCB_READONLY),
413 wxT("read-only combobox doesn't have any edit control") );
414
415 WXHWND hWndEdit = GetEditHWNDIfAvailable();
416 wxASSERT_MSG( hWndEdit, wxT("combobox without edit control?") );
417
418 return hWndEdit;
419 }
420
421 wxWindow *wxComboBox::GetEditableWindow()
422 {
423 wxASSERT_MSG( !HasFlag(wxCB_READONLY),
424 wxT("read-only combobox doesn't have any edit control") );
425
426 return this;
427 }
428
429 // ----------------------------------------------------------------------------
430 // wxComboBox creation
431 // ----------------------------------------------------------------------------
432
433 bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
434 const wxString& value,
435 const wxPoint& pos,
436 const wxSize& size,
437 int n, const wxString choices[],
438 long style,
439 const wxValidator& validator,
440 const wxString& name)
441 {
442 // pretend that wxComboBox is hidden while it is positioned and resized and
443 // show it only right before leaving this method because otherwise there is
444 // some noticeable flicker while the control rearranges itself
445 m_isShown = false;
446
447 if ( !CreateAndInit(parent, id, pos, size, n, choices, style,
448 validator, name) )
449 return false;
450
451 // we shouldn't call SetValue() for an empty string because this would
452 // (correctly) result in an assert with a read only combobox and is useless
453 // for the other ones anyhow
454 if ( !value.empty() )
455 SetValue(value);
456
457 // a (not read only) combobox is, in fact, 2 controls: the combobox itself
458 // and an edit control inside it and if we want to catch events from this
459 // edit control, we must subclass it as well
460 if ( !(style & wxCB_READONLY) )
461 {
462 gs_wndprocEdit = wxSetWindowProc((HWND)GetEditHWND(), wxComboEditWndProc);
463 }
464
465 // and finally, show the control
466 Show(true);
467
468 return true;
469 }
470
471 bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
472 const wxString& value,
473 const wxPoint& pos,
474 const wxSize& size,
475 const wxArrayString& choices,
476 long style,
477 const wxValidator& validator,
478 const wxString& name)
479 {
480 wxCArrayString chs(choices);
481 return Create(parent, id, value, pos, size, chs.GetCount(),
482 chs.GetStrings(), style, validator, name);
483 }
484
485 WXDWORD wxComboBox::MSWGetStyle(long style, WXDWORD *exstyle) const
486 {
487 // we never have an external border
488 WXDWORD msStyle = wxChoice::MSWGetStyle
489 (
490 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
491 );
492
493 // usually WS_TABSTOP is added by wxControl::MSWGetStyle() but as we're
494 // created hidden (see Create() above), it is not done for us but we still
495 // want to have this style
496 msStyle |= WS_TABSTOP;
497
498 // remove the style always added by wxChoice
499 msStyle &= ~CBS_DROPDOWNLIST;
500
501 if ( style & wxCB_READONLY )
502 msStyle |= CBS_DROPDOWNLIST;
503 #ifndef __WXWINCE__
504 else if ( style & wxCB_SIMPLE )
505 msStyle |= CBS_SIMPLE; // A list (shown always) and edit control
506 #endif
507 else
508 msStyle |= CBS_DROPDOWN;
509
510 // there is no reason to not always use CBS_AUTOHSCROLL, so do use it
511 msStyle |= CBS_AUTOHSCROLL;
512
513 // NB: we used to also add CBS_NOINTEGRALHEIGHT here but why?
514
515 return msStyle;
516 }
517
518 // ----------------------------------------------------------------------------
519 // wxComboBox text control-like methods
520 // ----------------------------------------------------------------------------
521
522 wxString wxComboBox::GetValue() const
523 {
524 return HasFlag(wxCB_READONLY) ? GetStringSelection()
525 : wxTextEntry::GetValue();
526 }
527
528 void wxComboBox::SetValue(const wxString& value)
529 {
530 if ( HasFlag(wxCB_READONLY) )
531 SetStringSelection(value);
532 else
533 wxTextEntry::SetValue(value);
534 }
535
536 void wxComboBox::Clear()
537 {
538 wxChoice::Clear();
539 if ( !HasFlag(wxCB_READONLY) )
540 wxTextEntry::Clear();
541 }
542
543 void wxComboBox::GetSelection(long *from, long *to) const
544 {
545 if ( !HasFlag(wxCB_READONLY) )
546 {
547 wxTextEntry::GetSelection(from, to);
548 }
549 else // text selection doesn't make sense for read only comboboxes
550 {
551 if ( from )
552 *from = -1;
553 if ( to )
554 *to = -1;
555 }
556 }
557
558 bool wxComboBox::IsEditable() const
559 {
560 return !HasFlag(wxCB_READONLY) && wxTextEntry::IsEditable();
561 }
562
563 // ----------------------------------------------------------------------------
564 // standard event handling
565 // ----------------------------------------------------------------------------
566
567 void wxComboBox::OnCut(wxCommandEvent& WXUNUSED(event))
568 {
569 Cut();
570 }
571
572 void wxComboBox::OnCopy(wxCommandEvent& WXUNUSED(event))
573 {
574 Copy();
575 }
576
577 void wxComboBox::OnPaste(wxCommandEvent& WXUNUSED(event))
578 {
579 Paste();
580 }
581
582 void wxComboBox::OnUndo(wxCommandEvent& WXUNUSED(event))
583 {
584 Undo();
585 }
586
587 void wxComboBox::OnRedo(wxCommandEvent& WXUNUSED(event))
588 {
589 Redo();
590 }
591
592 void wxComboBox::OnDelete(wxCommandEvent& WXUNUSED(event))
593 {
594 RemoveSelection();
595 }
596
597 void wxComboBox::OnSelectAll(wxCommandEvent& WXUNUSED(event))
598 {
599 SelectAll();
600 }
601
602 void wxComboBox::OnUpdateCut(wxUpdateUIEvent& event)
603 {
604 event.Enable( CanCut() );
605 }
606
607 void wxComboBox::OnUpdateCopy(wxUpdateUIEvent& event)
608 {
609 event.Enable( CanCopy() );
610 }
611
612 void wxComboBox::OnUpdatePaste(wxUpdateUIEvent& event)
613 {
614 event.Enable( CanPaste() );
615 }
616
617 void wxComboBox::OnUpdateUndo(wxUpdateUIEvent& event)
618 {
619 event.Enable( IsEditable() && CanUndo() );
620 }
621
622 void wxComboBox::OnUpdateRedo(wxUpdateUIEvent& event)
623 {
624 event.Enable( IsEditable() && CanRedo() );
625 }
626
627 void wxComboBox::OnUpdateDelete(wxUpdateUIEvent& event)
628 {
629 event.Enable(IsEditable() && HasSelection());
630 }
631
632 void wxComboBox::OnUpdateSelectAll(wxUpdateUIEvent& event)
633 {
634 event.Enable(IsEditable() && !wxTextEntry::IsEmpty());
635 }
636
637 #if wxUSE_TOOLTIPS
638
639 void wxComboBox::DoSetToolTip(wxToolTip *tip)
640 {
641 wxChoice::DoSetToolTip(tip);
642
643 if ( tip && !HasFlag(wxCB_READONLY) )
644 tip->AddOtherWindow(GetEditHWND());
645 }
646
647 #endif // wxUSE_TOOLTIPS
648
649 #if wxUSE_UXTHEME
650
651 bool wxComboBox::SetHint(const wxString& hintOrig)
652 {
653 wxString hint(hintOrig);
654 if ( wxUxThemeEngine::GetIfActive() )
655 {
656 // under XP (but not Vista) there is a bug in cue banners
657 // implementation for combobox edit control: the first character is
658 // partially chopped off, so prepend a space to make it fully visible
659 hint.insert(0, " ");
660 }
661
662 return wxTextEntry::SetHint(hint);
663 }
664
665 #endif // wxUSE_UXTHEME
666
667 #endif // wxUSE_COMBOBOX