Ensure that Enter key presses are never stolen from wxButton in wxMSW.
[wxWidgets.git] / src / msw / button.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/button.cpp
3 // Purpose: wxButton
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
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_BUTTON
28
29 #include "wx/button.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/app.h"
33 #include "wx/brush.h"
34 #include "wx/panel.h"
35 #include "wx/bmpbuttn.h"
36 #include "wx/settings.h"
37 #include "wx/dcscreen.h"
38 #include "wx/dcclient.h"
39 #include "wx/toplevel.h"
40 #include "wx/msw/wrapcctl.h"
41 #include "wx/msw/private.h"
42 #include "wx/msw/missing.h"
43 #endif
44
45 #include "wx/imaglist.h"
46 #include "wx/stockitem.h"
47 #include "wx/msw/private/button.h"
48 #include "wx/msw/private/dc.h"
49 #include "wx/private/window.h"
50
51 #if wxUSE_MARKUP
52 #include "wx/generic/private/markuptext.h"
53 #endif // wxUSE_MARKUP
54
55 // set the value for BCM_SETSHIELD (for the UAC shield) if it's not defined in
56 // the header
57 #ifndef BCM_SETSHIELD
58 #define BCM_SETSHIELD 0x160c
59 #endif
60
61 // ----------------------------------------------------------------------------
62 // macros
63 // ----------------------------------------------------------------------------
64
65 BEGIN_EVENT_TABLE(wxButton, wxButtonBase)
66 EVT_CHAR_HOOK(wxButton::OnCharHook)
67 END_EVENT_TABLE()
68
69 // ============================================================================
70 // implementation
71 // ============================================================================
72
73 // ----------------------------------------------------------------------------
74 // creation/destruction
75 // ----------------------------------------------------------------------------
76
77 bool wxButton::Create(wxWindow *parent,
78 wxWindowID id,
79 const wxString& lbl,
80 const wxPoint& pos,
81 const wxSize& size,
82 long style,
83 const wxValidator& validator,
84 const wxString& name)
85 {
86 wxString label(lbl);
87 if (label.empty() && wxIsStockID(id))
88 {
89 // On Windows, some buttons aren't supposed to have mnemonics
90 label = wxGetStockLabel
91 (
92 id,
93 id == wxID_OK || id == wxID_CANCEL || id == wxID_CLOSE
94 ? wxSTOCK_NOFLAGS
95 : wxSTOCK_WITH_MNEMONIC
96 );
97 }
98
99 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
100 return false;
101
102 WXDWORD exstyle;
103 WXDWORD msStyle = MSWGetStyle(style, &exstyle);
104
105 // if the label contains several lines we must explicitly tell the button
106 // about it or it wouldn't draw it correctly ("\n"s would just appear as
107 // black boxes)
108 //
109 // NB: we do it here and not in MSWGetStyle() because we need the label
110 // value and the label is not set yet when MSWGetStyle() is called
111 msStyle |= wxMSWButton::GetMultilineStyle(label);
112
113 return MSWCreateControl(wxT("BUTTON"), msStyle, pos, size, label, exstyle);
114 }
115
116 wxButton::~wxButton()
117 {
118 wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(this), wxTopLevelWindow);
119 if ( tlw && tlw->GetTmpDefaultItem() == this )
120 {
121 UnsetTmpDefault();
122 }
123 }
124
125 // ----------------------------------------------------------------------------
126 // flags
127 // ----------------------------------------------------------------------------
128
129 WXDWORD wxButton::MSWGetStyle(long style, WXDWORD *exstyle) const
130 {
131 // buttons never have an external border, they draw their own one
132 WXDWORD msStyle = wxControl::MSWGetStyle
133 (
134 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
135 );
136
137 // we must use WS_CLIPSIBLINGS with the buttons or they would draw over
138 // each other in any resizable dialog which has more than one button in
139 // the bottom
140 msStyle |= WS_CLIPSIBLINGS;
141
142 // don't use "else if" here: weird as it is, but you may combine wxBU_LEFT
143 // and wxBU_RIGHT to get BS_CENTER!
144 if ( style & wxBU_LEFT )
145 msStyle |= BS_LEFT;
146 if ( style & wxBU_RIGHT )
147 msStyle |= BS_RIGHT;
148 if ( style & wxBU_TOP )
149 msStyle |= BS_TOP;
150 if ( style & wxBU_BOTTOM )
151 msStyle |= BS_BOTTOM;
152 #ifndef __WXWINCE__
153 // flat 2d buttons
154 if ( style & wxNO_BORDER )
155 msStyle |= BS_FLAT;
156 #endif // __WXWINCE__
157
158 return msStyle;
159 }
160
161 /* static */
162 wxSize wxButtonBase::GetDefaultSize()
163 {
164 static wxSize s_sizeBtn;
165
166 if ( s_sizeBtn.x == 0 )
167 {
168 wxScreenDC dc;
169 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
170
171 // The size of a standard button in the dialog units is 50x14,
172 // translate this to pixels.
173 //
174 // Windows' computes dialog units using average character width over
175 // upper- and lower-case ASCII alphabet and not using the average
176 // character width metadata stored in the font; see
177 // http://support.microsoft.com/default.aspx/kb/145994 for detailed
178 // discussion.
179 //
180 // NB: wxMulDivInt32() is used, because it correctly rounds the result
181
182 const wxSize base = wxPrivate::GetAverageASCIILetterSize(dc);
183 s_sizeBtn.x = wxMulDivInt32(50, base.x, 4);
184 s_sizeBtn.y = wxMulDivInt32(14, base.y, 8);
185 }
186
187 return s_sizeBtn;
188 }
189
190 // ----------------------------------------------------------------------------
191 // default button handling
192 // ----------------------------------------------------------------------------
193
194 /*
195 The comment below and all this code is probably due to not using WM_NEXTDLGCTL
196 message when changing focus (but just SetFocus() which is not enough), see
197 http://blogs.msdn.com/oldnewthing/archive/2004/08/02/205624.aspx for the
198 full explanation.
199
200 TODO: Do use WM_NEXTDLGCTL and get rid of all this code.
201
202
203 "Everything you ever wanted to know about the default buttons" or "Why do we
204 have to do all this?"
205
206 In MSW the default button should be activated when the user presses Enter
207 and the current control doesn't process Enter itself somehow. This is
208 handled by ::DefWindowProc() (or maybe ::DefDialogProc()) using DM_SETDEFID
209 Another aspect of "defaultness" is that the default button has different
210 appearance: this is due to BS_DEFPUSHBUTTON style which is completely
211 separate from DM_SETDEFID stuff (!). Also note that BS_DEFPUSHBUTTON should
212 be unset if our parent window is not active so it should be unset whenever
213 we lose activation and set back when we regain it.
214
215 Final complication is that when a button is active, it should be the default
216 one, i.e. pressing Enter on a button always activates it and not another
217 one.
218
219 We handle this by maintaining a permanent and a temporary default items in
220 wxControlContainer (both may be NULL). When a button becomes the current
221 control (i.e. gets focus) it sets itself as the temporary default which
222 ensures that it has the right appearance and that Enter will be redirected
223 to it. When the button loses focus, it unsets the temporary default and so
224 the default item will be the permanent default -- that is the default button
225 if any had been set or none otherwise, which is just what we want.
226
227 NB: all this is quite complicated by now and the worst is that normally
228 it shouldn't be necessary at all as for the normal Windows programs
229 DefWindowProc() and IsDialogMessage() take care of all this
230 automatically -- however in wxWidgets programs this doesn't work for
231 nested hierarchies (i.e. a notebook inside a notebook) for unknown
232 reason and so we have to reproduce all this code ourselves. It would be
233 very nice if we could avoid doing it.
234 */
235
236 // set this button as the (permanently) default one in its panel
237 wxWindow *wxButton::SetDefault()
238 {
239 // set this one as the default button both for wxWidgets ...
240 wxWindow *winOldDefault = wxButtonBase::SetDefault();
241
242 // ... and Windows
243 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), false);
244 SetDefaultStyle(this, true);
245
246 return winOldDefault;
247 }
248
249 // return the top level parent window if it's not being deleted yet, otherwise
250 // return NULL
251 static wxTopLevelWindow *GetTLWParentIfNotBeingDeleted(wxWindow *win)
252 {
253 for ( ;; )
254 {
255 // IsTopLevel() will return false for a wxTLW being deleted, so we also
256 // need the parent test for this case
257 wxWindow * const parent = win->GetParent();
258 if ( !parent || win->IsTopLevel() )
259 {
260 if ( win->IsBeingDeleted() )
261 return NULL;
262
263 break;
264 }
265
266 win = parent;
267 }
268
269 wxASSERT_MSG( win, wxT("button without top level parent?") );
270
271 wxTopLevelWindow * const tlw = wxDynamicCast(win, wxTopLevelWindow);
272 wxASSERT_MSG( tlw, wxT("logic error in GetTLWParentIfNotBeingDeleted()") );
273
274 return tlw;
275 }
276
277 // set this button as being currently default
278 void wxButton::SetTmpDefault()
279 {
280 wxTopLevelWindow * const tlw = GetTLWParentIfNotBeingDeleted(GetParent());
281 if ( !tlw )
282 return;
283
284 wxWindow *winOldDefault = tlw->GetDefaultItem();
285 tlw->SetTmpDefaultItem(this);
286
287 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), false);
288 SetDefaultStyle(this, true);
289 }
290
291 // unset this button as currently default, it may still stay permanent default
292 void wxButton::UnsetTmpDefault()
293 {
294 wxTopLevelWindow * const tlw = GetTLWParentIfNotBeingDeleted(GetParent());
295 if ( !tlw )
296 return;
297
298 tlw->SetTmpDefaultItem(NULL);
299
300 wxWindow *winOldDefault = tlw->GetDefaultItem();
301
302 SetDefaultStyle(this, false);
303 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), true);
304 }
305
306 /* static */
307 void
308 wxButton::SetDefaultStyle(wxButton *btn, bool on)
309 {
310 // we may be called with NULL pointer -- simpler to do the check here than
311 // in the caller which does wxDynamicCast()
312 if ( !btn )
313 return;
314
315 // first, let DefDlgProc() know about the new default button
316 if ( on )
317 {
318 // we shouldn't set BS_DEFPUSHBUTTON for any button if we don't have
319 // focus at all any more
320 if ( !wxTheApp->IsActive() )
321 return;
322
323 wxWindow * const tlw = wxGetTopLevelParent(btn);
324 wxCHECK_RET( tlw, wxT("button without top level window?") );
325
326 ::SendMessage(GetHwndOf(tlw), DM_SETDEFID, btn->GetId(), 0L);
327
328 // sending DM_SETDEFID also changes the button style to
329 // BS_DEFPUSHBUTTON so there is nothing more to do
330 }
331
332 // then also change the style as needed
333 long style = ::GetWindowLong(GetHwndOf(btn), GWL_STYLE);
334 if ( !(style & BS_DEFPUSHBUTTON) == on )
335 {
336 // don't do it with the owner drawn buttons because it will
337 // reset BS_OWNERDRAW style bit too (as BS_OWNERDRAW &
338 // BS_DEFPUSHBUTTON != 0)!
339 if ( (style & BS_OWNERDRAW) != BS_OWNERDRAW )
340 {
341 ::SendMessage(GetHwndOf(btn), BM_SETSTYLE,
342 on ? style | BS_DEFPUSHBUTTON
343 : style & ~BS_DEFPUSHBUTTON,
344 1L /* redraw */);
345 }
346 else // owner drawn
347 {
348 // redraw the button - it will notice itself that it's
349 // [not] the default one [any longer]
350 btn->Refresh();
351 }
352 }
353 //else: already has correct style
354 }
355
356 // ----------------------------------------------------------------------------
357 // helpers
358 // ----------------------------------------------------------------------------
359
360 bool wxButton::SendClickEvent()
361 {
362 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, GetId());
363 event.SetEventObject(this);
364
365 return ProcessCommand(event);
366 }
367
368 void wxButton::Command(wxCommandEvent & event)
369 {
370 ProcessCommand(event);
371 }
372
373 // ----------------------------------------------------------------------------
374 // event/message handlers
375 // ----------------------------------------------------------------------------
376
377 void wxButton::OnCharHook(wxKeyEvent& event)
378 {
379 // We want to ensure that the button always processes Enter key events
380 // itself, even if it's inside some control that normally takes over them
381 // (this happens when the button is part of an in-place editor control for
382 // example).
383 if ( event.GetKeyCode() == WXK_RETURN )
384 {
385 // We should ensure that subsequent key events are still generated even
386 // if we did handle EVT_CHAR_HOOK (normally this would suppress their
387 // generation).
388 event.DoAllowNextEvent();
389 }
390 else
391 {
392 event.Skip();
393 }
394 }
395
396 bool wxButton::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
397 {
398 bool processed = false;
399 switch ( param )
400 {
401 // NOTE: Apparently older versions (NT 4?) of the common controls send
402 // BN_DOUBLECLICKED but not a second BN_CLICKED for owner-drawn
403 // buttons, so in order to send two EVT_BUTTON events we should
404 // catch both types. Currently (Feb 2003) up-to-date versions of
405 // win98, win2k and winXP all send two BN_CLICKED messages for
406 // all button types, so we don't catch BN_DOUBLECLICKED anymore
407 // in order to not get 3 EVT_BUTTON events. If this is a problem
408 // then we need to figure out which version of the comctl32 changed
409 // this behaviour and test for it.
410
411 case 1: // message came from an accelerator
412 case BN_CLICKED: // normal buttons send this
413 processed = SendClickEvent();
414 break;
415 }
416
417 return processed;
418 }
419
420 WXLRESULT wxButton::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
421 {
422 // when we receive focus, we want to temporarily become the default button in
423 // our parent panel so that pressing "Enter" would activate us -- and when
424 // losing it we should restore the previous default button as well
425 if ( nMsg == WM_SETFOCUS )
426 {
427 SetTmpDefault();
428
429 // let the default processing take place too
430 }
431 else if ( nMsg == WM_KILLFOCUS )
432 {
433 UnsetTmpDefault();
434 }
435
436 // let the base class do all real processing
437 return wxAnyButton::MSWWindowProc(nMsg, wParam, lParam);
438 }
439
440 // ----------------------------------------------------------------------------
441 // authentication needed handling
442 // ----------------------------------------------------------------------------
443
444 bool wxButton::DoGetAuthNeeded() const
445 {
446 return m_authNeeded;
447 }
448
449 void wxButton::DoSetAuthNeeded(bool show)
450 {
451 // show/hide UAC symbol on Windows Vista and later
452 if ( wxGetWinVersion() >= wxWinVersion_6 )
453 {
454 m_authNeeded = show;
455 ::SendMessage(GetHwnd(), BCM_SETSHIELD, 0, show);
456 InvalidateBestSize();
457 }
458 }
459
460 #endif // wxUSE_BUTTON
461