fix wxWindow::PushEventHandler and related wxWindow functions for the stack managemen...
[wxWidgets.git] / docs / doxygen / overviews / eventhandling.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: eventhandling.h
3 // Purpose: topic overview
4 // Author: wxWidgets team
5 // RCS-ID: $Id$
6 // Licence: wxWindows license
7 /////////////////////////////////////////////////////////////////////////////
8
9 /**
10
11 @page overview_eventhandling Event Handling
12
13 Classes: wxEvtHandler, wxWindow, wxEvent
14
15 @li @ref overview_eventhandling_introduction
16 @li @ref overview_eventhandling_eventtables
17 @li @ref overview_eventhandling_connect
18 @li @ref overview_eventhandling_processing
19 @li @ref overview_eventhandling_propagation
20 @li @ref overview_eventhandling_virtual
21 @li @ref overview_eventhandling_prog
22 @li @ref overview_eventhandling_pluggable
23 @li @ref overview_eventhandling_winid
24 @li @ref overview_eventhandling_custom
25 @li @ref overview_eventhandling_macros
26
27
28 <hr>
29
30
31 @section overview_eventhandling_introduction Introduction
32
33 There are two principal ways to handle events in wxWidgets. One of them uses
34 <em>event table</em> macros and allows you to define the connection between events
35 and their handlers only statically, i.e., during program compilation. The other
36 one uses wxEvtHandler::Connect() call and can be used to connect, and
37 disconnect, the handlers dynamically, i.e., during run-time depending on some
38 conditions. It also allows the direct connection of the events of one object to a
39 handler method in another object. The static event tables can only handle
40 events in the object where they are defined so using Connect() is more flexible
41 than using the event tables. On the other hand, event tables are more succinct
42 and centralize all event handlers connection in one place. You can either
43 choose a single approach that you find preferable or freely combine both
44 methods in your program in different classes or even in one and the same class,
45 although this is probably sufficiently confusing to be a bad idea.
46
47 But before you make this choice, let us discuss these two ways in more
48 detail. In the next section we provide a short introduction to handling the
49 events using the event tables. Please see @ref overview_eventhandling_connect
50 for the discussion of Connect().
51
52 @section overview_eventhandling_eventtables Event Handling with Event Tables
53
54 To use an <em>event table</em> you must first decide in which class you wish to
55 handle the events. The only requirement imposed by wxWidgets is that this class
56 must derive from wxEvtHandler and so, considering that wxWindow derives from
57 it, any classes representing windows can handle events. Simple events such as
58 menu commands are usually processed at the level of a top-level window
59 containing the menu, so let's suppose that you need to handle some events in @c
60 MyFrame class deriving from wxFrame.
61
62 First define one or more <em>event handlers</em>. They
63 are just simple (non-virtual) methods of the class that take as a parameter a
64 reference to an object of a wxEvent-derived class and have no return value (any
65 return information is passed via the argument, which is why it is non-const).
66 You also need to insert a macro
67
68 @code
69 DECLARE_EVENT_TABLE()
70 @endcode
71
72 somewhere in the class declaration. It doesn't matter where it appears but
73 it's customary to put it at the end because the macro changes the access
74 type internally so it's safest if nothing follows it. The
75 full class declaration might look like this:
76
77 @code
78 class MyFrame : public wxFrame
79 {
80 public:
81 MyFrame(...) : wxFrame(...) { }
82
83 ...
84
85 protected:
86 int m_whatever;
87
88 private:
89 // Notice that as the event handlers normally are not called from outside
90 // the class, they normally are private. In particular they don't need
91 // to be public.
92 void OnExit(wxCommandEvent& event);
93 void OnButton1(wxCommandEvent& event);
94 void OnSize(wxSizeEvent& event);
95
96 // it's common to call the event handlers OnSomething() but there is no
97 // obligation to do that; this one is an event handler too:
98 void DoTest(wxCommandEvent& event);
99
100 DECLARE_EVENT_TABLE()
101 };
102 @endcode
103
104 Next the event table must be defined and, as with any definition, it must be
105 placed in an implementation file. The event table tells wxWidgets how to map
106 events to member functions and in our example it could look like this:
107
108 @code
109 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
110 EVT_MENU(wxID_EXIT, MyFrame::OnExit)
111 EVT_MENU(DO_TEST, MyFrame::DoTest)
112 EVT_SIZE(MyFrame::OnSize)
113 EVT_BUTTON(BUTTON1, MyFrame::OnButton1)
114 END_EVENT_TABLE()
115 @endcode
116
117 Notice that you must mention a method you want to use for the event handling in
118 the event table definition; just defining it in MyFrame class is @e not enough.
119
120 Let us now look at the details of this definition: the first line means that we
121 are defining the event table for MyFrame class and that its base class is
122 wxFrame, so events not processed by MyFrame will, by default, be handled by
123 wxFrame. The next four lines define connections of individual events to their
124 handlers: the first two of them map menu commands from the items with the
125 identifiers specified as the first macro parameter to two different member
126 functions. In the next one, @c EVT_SIZE means that any changes in the size of
127 the frame will result in calling OnSize() method. Note that this macro doesn't
128 need a window identifier, since normally you are only interested in the current
129 window's size events.
130
131 The @c EVT_BUTTON macro demonstrates that the originating event does not have to
132 come from the window class implementing the event table -- if the event source
133 is a button within a panel within a frame, this will still work, because event
134 tables are searched up through the hierarchy of windows for the command events.
135 (But only command events, so you can't catch mouse move events in a child
136 control in the parent window in the same way because wxMouseEvent doesn't
137 derive from wxCommandEvent. See below for how you can do it.) In this case, the
138 button's event table will be searched, then the parent panel's, then the
139 frame's.
140
141 Finally, you need to implement the event handlers. As mentioned before, all
142 event handlers take a wxEvent-derived argument whose exact class differs
143 according to the type of event and the class of the originating window. For
144 size events, wxSizeEvent is used. For menu commands and most control commands
145 (such as button presses), wxCommandEvent is used. When controls get more
146 complicated, more specific wxCommandEvent-derived event classes providing
147 additional control-specific information can be used, such as wxTreeEvent for
148 events from wxTreeCtrl windows.
149
150 In the simplest possible case an event handler may not use the @c event
151 parameter at all. For example,
152
153 @code
154 void MyFrame::OnExit(wxCommandEvent& WXUNUSED(event))
155 {
156 // when the user selects "Exit" from the menu we should close
157 Close(true);
158 }
159 @endcode
160
161 In other cases you may need some information carried by the @c event argument,
162 as in:
163
164 @code
165 void MyFrame::OnSize(wxSizeEvent& event)
166 {
167 wxSize size = event.GetSize();
168
169 ... update the frame using the new size ...
170 }
171 @endcode
172
173 You will find the details about the event table macros and the corresponding
174 wxEvent-derived classes in the discussion of each control generating these
175 events.
176
177
178 @section overview_eventhandling_connect Dynamic Event Handling
179
180 As with the event tables, decide in which class you intend to
181 handle the events first and, as before, this class must derive from
182 wxEvtHandler (usually indirectly via wxWindow). See the declaration of MyFrame
183 in the previous section. However the similarities end here and both the syntax
184 and the possibilities of handling events in this way are rather different.
185
186 Let us start by looking at the syntax: the first obvious difference is that you
187 need not use DECLARE_EVENT_TABLE() nor BEGIN_EVENT_TABLE() and the
188 associated macros. Instead, in any place in your code, but usually in
189 the code of the class defining the handler itself (and definitely not in the
190 global scope as with the event tables), call its Connect() method like this:
191
192 @code
193 MyFrame::MyFrame(...)
194 {
195 Connect(wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED,
196 wxCommandEventHandler(MyFrame::OnExit));
197 }
198 @endcode
199
200 This class should be self-explanatory except for wxCommandEventHandler part:
201 this is a macro that ensures that the method is of the correct type by using
202 static_cast in the same way as the event table macros.
203
204 Now let us describe the semantic differences:
205 <ul>
206 <li>
207 Event handlers can be connected at any moment. For example, it's possible
208 to do some initialization first and only connect the handlers if and when
209 it succeeds. This can avoid the need to test that the object was properly
210 initialized in the event handlers themselves. With Connect() they
211 simply won't be called if it wasn't correctly initialized.
212 </li>
213
214 <li>
215 As a slight extension of the above, the handlers can also be
216 Disconnect()-ed at any time and maybe later reconnected. Of course,
217 it's also possible to emulate this behaviour with the classic
218 static (i.e., connected via event tables) handlers by using an internal
219 flag indicating whether the handler is currently enabled and returning
220 from it if it isn't, but using dynamically connected handlers requires
221 less code and is also usually more clear.
222 </li>
223
224 <li>
225 Also notice that you must derive a class inherited from, say,
226 wxTextCtrl even if you don't want to modify the control behaviour at
227 all but just want to handle some of its events. This is especially
228 inconvenient when the control is loaded from the XRC. Connecting the
229 event handler dynamically bypasses the need for this unwanted
230 sub-classing.
231 </li>
232
233 <li>
234 Last but very, very far from least is the possibility to connect an
235 event of some object to a method of another object. This is impossible
236 to do with event tables because it is not possible to specify the
237 object to dispatch the event to so it necessarily needs to be sent to
238 the same object which generated the event. Not so with Connect() which
239 has an optional @c eventSink parameter that can be used to specify the
240 object which will handle the event. Of course, in this case the method
241 being connected must belong to the class that is the type of the
242 @c eventSink object! To give a quick example, people often want to catch
243 mouse movement events happening when the mouse is in one of the frame
244 children in the frame itself. Doing it in a naive way doesn't work:
245 <ul>
246 <li>
247 A @c EVT_LEAVE_WINDOW(MyFrame::OnMouseLeave) line in the frame
248 event table has no effect as mouse move (including entering and
249 leaving) events are not propagated up to the parent window
250 (at least not by default).
251 </li>
252
253 <li>
254 Putting the same line in a child event table will crash during
255 run-time because the MyFrame method will be called on a wrong
256 object -- it's easy to convince oneself that the only object
257 that can be used here is the pointer to the child, as
258 wxWidgets has nothing else. But calling a frame method with the
259 child window pointer instead of the pointer to the frame is, of
260 course, disastrous.
261 </li>
262 </ul>
263
264 However writing
265 @code
266 MyFrame::MyFrame(...)
267 {
268 m_child->Connect(wxID_ANY, wxEVT_LEAVE_WINDOW,
269 wxMouseEventHandler(MyFrame::OnMouseLeave),
270 NULL, // unused extra data parameter
271 this); // this indicates the object to connect to
272 }
273 @endcode
274 will work exactly as expected. Note that you can get the object that
275 generated the event -- and that is not the same as the frame -- via
276 wxEvent::GetEventObject() method of @c event argument passed to the
277 event handler.
278 </li>
279 </ul>
280
281 To summarize, using Connect() requires slightly more typing but is much more
282 flexible than using static event tables so don't hesitate to use it when you
283 need this extra power. On the other hand, event tables are still perfectly fine
284 in simple situations where this extra flexibility is not needed.
285
286
287 @section overview_eventhandling_processing How Events are Processed
288
289 The previous sections explain how to define event handlers but don't address
290 the question of how exactly wxWidgets finds the handler to call for the
291 given event. This section describes the algorithm used in detail.
292
293 When an event is received from the windowing system, wxWidgets calls
294 wxEvtHandler::ProcessEvent() on the first event handler object belonging to the
295 window generating the event. The normal order of event table searching by
296 ProcessEvent() is as follows, with the event processing stopping as soon as a
297 handler is found (unless the handler calls wxEvent::Skip() in which case it
298 doesn't count as having handled the event and the search continues):
299 <ol>
300 <li value="0">
301 Before anything else happens, wxApp::FilterEvent() is called. If it returns
302 anything but -1 (default), the event handling stops immediately.
303 </li>
304
305 <li value="1">
306 If this event handler is disabled via a call to
307 wxEvtHandler::SetEvtHandlerEnabled() the next three steps are skipped and
308 the event handler resumes at step (5).
309 </li>
310
311 <li value="2">
312 If the object is a wxWindow and has an associated validator, wxValidator
313 gets a chance to process the event.
314 </li>
315
316 <li value="3">
317 The list of dynamically connected event handlers, i.e., those for which
318 Connect() was called, is consulted. Notice that this is done before
319 checking the static event table entries, so if both a dynamic and a static
320 event handler match the same event, the static one is never going to be
321 used.
322 </li>
323
324 <li value="4">
325 The event table containing all the handlers defined using the event table
326 macros in this class and its base classes is examined. Notice that this
327 means that any event handler defined in a base class will be executed at
328 this step.
329 </li>
330
331 <li value="5">
332 The event is passed to the next event handler, if any, in the event handler
333 chain, i.e., the steps (1) to (4) are done for it. This chain can be formed
334 using wxEvtHandler::SetNextHandler():
335 @image html overview_eventhandling_chain.png
336 (referring to the image, if @c A->ProcessEvent is called and it doesn't handle
337 the event, @c B->ProcessEvent will be called and so on...).
338 In the case of wxWindow you can build a stack (implemented using wxEvtHandler
339 double-linked list) using wxWindow::PushEventHandler():
340 @image html overview_eventhandling_winstack.png
341 (referring to the image, if @c W->ProcessEvent is called, it immediately calls
342 @c A->ProcessEvent; if nor @c A nor @c B handle the event, then the wxWindow
343 itself is used - i.e. the dynamically connected event handlers and static
344 event table entries of wxWindow are looked as the last possibility, after
345 all pushed event handlers were tested).
346 Note however that usually there are no wxEvtHandler chains nor wxWindows stacks
347 so this step will usually do anything.
348 </li>
349
350 <li value="6">
351 If the object is a wxWindow and the event is set to propagate (by default
352 only wxCommandEvent-derived events are set to propagate), then the
353 processing restarts from the step (1) (and excluding the step (7)) for the
354 parent window. If this object is not a window but the next handler exists,
355 the event is passed to its parent if it is a window. This ensures that in a
356 common case of (possibly several) non-window event handlers pushed on top
357 of a window, the event eventually reaches the window parent.
358 </li>
359
360 <li value="7">
361 Finally, i.e., if the event is still not processed, the wxApp object itself
362 (which derives from wxEvtHandler) gets a last chance to process it.
363 </li>
364 </ol>
365
366 <em>Please pay close attention to step 6!</em> People often overlook or get
367 confused by this powerful feature of the wxWidgets event processing system. The
368 details of event propagation up the window hierarchy are described in the
369 next section.
370
371 Also please notice that there are additional steps in the event handling for
372 the windows-making part of wxWidgets document-view framework, i.e.,
373 wxDocParentFrame, wxDocChildFrame and their MDI equivalents wxDocMDIParentFrame
374 and wxDocMDIChildFrame. The parent frame classes modify step (2) above to
375 send the events received by them to wxDocManager object first. This object, in
376 turn, sends the event to the current view and the view itself lets its
377 associated document process the event first. The child frame classes send
378 the event directly to the associated view which still forwards it to its
379 document object. Notice that to avoid remembering the exact order in which the
380 events are processed in the document-view frame, the simplest, and recommended,
381 solution is to only handle the events at the view classes level, and not in the
382 document or document manager classes
383
384
385 @section overview_eventhandling_propagation How Events Propagate Upwards
386
387 As mentioned in the previous section, the events of the classes deriving from
388 wxCommandEvent are propagated by default to the parent window if they are not
389 processed in this window itself. But although by default only the command
390 events are propagated like this, other events can be propagated as well because
391 the event handling code uses wxEvent::ShouldPropagate() to check whether an
392 event should be propagated. It is also possible to propagate the event only a
393 limited number of times and not until it is processed (or a top level parent
394 window is reached).
395
396 Finally, there is another additional complication (which, in fact, simplifies
397 life of wxWidgets programmers significantly): when propagating the command
398 events up to the parent window, the event propagation stops when it
399 reaches the parent dialog, if any. This means that you don't risk getting
400 unexpected events from the dialog controls (which might be left unprocessed by
401 the dialog itself because it doesn't care about them) when a modal dialog is
402 popped up. The events do propagate beyond the frames, however. The rationale
403 for this choice is that there are only a few frames in a typical application
404 and their parent-child relation are well understood by the programmer while it
405 may be difficult, if not impossible, to track down all the dialogs that
406 may be popped up in a complex program (remember that some are created
407 automatically by wxWidgets). If you need to specify a different behaviour for
408 some reason, you can use wxWindow::SetExtraStyle(wxWS_EX_BLOCK_EVENTS)
409 explicitly to prevent the events from being propagated beyond the given window
410 or unset this flag for the dialogs that have it on by default.
411
412 Typically events that deal with a window as a window (size, motion,
413 paint, mouse, keyboard, etc.) are sent only to the window. Events
414 that have a higher level of meaning or are generated by the window
415 itself, (button click, menu select, tree expand, etc.) are command
416 events and are sent up to the parent to see if it is interested in the event.
417
418 As mentioned above, only command events are recursively applied to the parents
419 event handler in the library itself. As this quite often causes confusion for
420 users, here is a list of system events that will @em not get sent to the
421 parent's event handler:
422
423 @li wxEvent: The event base class
424 @li wxActivateEvent: A window or application activation event
425 @li wxCloseEvent: A close window or end session event
426 @li wxEraseEvent: An erase background event
427 @li wxFocusEvent: A window focus event
428 @li wxKeyEvent: A keypress event
429 @li wxIdleEvent: An idle event
430 @li wxInitDialogEvent: A dialog initialisation event
431 @li wxJoystickEvent: A joystick event
432 @li wxMenuEvent: A menu event
433 @li wxMouseEvent: A mouse event
434 @li wxMoveEvent: A move event
435 @li wxPaintEvent: A paint event
436 @li wxQueryLayoutInfoEvent: Used to query layout information
437 @li wxSetCursorEvent: Used for special cursor processing based on current mouse position
438 @li wxSizeEvent: A size event
439 @li wxScrollWinEvent: A scroll event sent by a scrolled window (not a scroll bar)
440 @li wxSysColourChangedEvent: A system colour change event
441
442 In some cases, it might be desired by the programmer to get a certain number
443 of system events in a parent window, for example all key events sent to, but not
444 used by, the native controls in a dialog. In this case, a special event handler
445 will have to be written that will override ProcessEvent() in order to pass
446 all events (or any selection of them) to the parent window.
447
448
449 @section overview_eventhandling_virtual Event Handlers vs Virtual Methods
450
451 It may be noted that wxWidgets' event processing system implements something
452 close to virtual methods in normal C++ in spirit: both of these mechanisms
453 allow you to alter the behaviour of the base class by defining the event handling
454 functions in the derived classes.
455
456 There is however an important difference between the two mechanisms when you
457 want to invoke the default behaviour, as implemented by the base class, from a
458 derived class handler. With the virtual functions, you need to call the base
459 class function directly and you can do it either in the beginning of the
460 derived class handler function (to post-process the event) or at its end (to
461 pre-process the event). With the event handlers, you only have the option of
462 pre-processing the events and in order to still let the default behaviour
463 happen you must call wxEvent::Skip() and @em not call the base class event
464 handler directly. In fact, the event handler probably doesn't even exist in the
465 base class as the default behaviour is often implemented in platform-specific
466 code by the underlying toolkit or OS itself. But even if it does exist at
467 wxWidgets level, it should never be called directly as the event handlers are
468 not part of wxWidgets API and should never be called directly.
469
470 Finally, please notice that the event handlers themselves shouldn't be virtual.
471 They should always be non-virtual and usually private (as there is no need to
472 make them public) methods of a wxEvtHandler-derived class.
473
474
475 @section overview_eventhandling_prog User Generated Events vs Programmatically Generated Events
476
477 While generically wxEvents can be generated both by user
478 actions (e.g., resize of a wxWindow) and by calls to functions
479 (e.g., wxWindow::SetSize), wxWidgets controls normally send wxCommandEvent-derived
480 events only for the user-generated events. The only @b exceptions to this rule are:
481
482 @li wxNotebook::AddPage: No event-free alternatives
483 @li wxNotebook::AdvanceSelection: No event-free alternatives
484 @li wxNotebook::DeletePage: No event-free alternatives
485 @li wxNotebook::SetSelection: Use wxNotebook::ChangeSelection instead, as
486 wxNotebook::SetSelection is deprecated
487 @li wxTreeCtrl::Delete: No event-free alternatives
488 @li wxTreeCtrl::DeleteAllItems: No event-free alternatives
489 @li wxTreeCtrl::EditLabel: No event-free alternatives
490 @li All wxTextCtrl methods
491
492 wxTextCtrl::ChangeValue can be used instead of wxTextCtrl::SetValue but the other
493 functions, such as wxTextCtrl::Replace or wxTextCtrl::WriteText don't have event-free
494 equivalents.
495
496
497
498 @section overview_eventhandling_pluggable Pluggable Event Handlers
499
500 In fact, you don't have to derive a new class from a window class
501 if you don't want to. You can derive a new class from wxEvtHandler instead,
502 defining the appropriate event table, and then call wxWindow::SetEventHandler
503 (or, preferably, wxWindow::PushEventHandler) to make this
504 event handler the object that responds to events. This way, you can avoid
505 a lot of class derivation, and use instances of the same event handler class (but different
506 objects as the same event handler object shouldn't be used more than once) to
507 handle events from instances of different widget classes.
508
509 If you ever have to call a window's event handler
510 manually, use the GetEventHandler function to retrieve the window's event handler and use that
511 to call the member function. By default, GetEventHandler returns a pointer to the window itself
512 unless an application has redirected event handling using SetEventHandler or PushEventHandler.
513
514 One use of PushEventHandler is to temporarily or permanently change the
515 behaviour of the GUI. For example, you might want to invoke a dialog editor
516 in your application that changes aspects of dialog boxes. You can
517 grab all the input for an existing dialog box, and edit it 'in situ',
518 before restoring its behaviour to normal. So even if the application
519 has derived new classes to customize behaviour, your utility can indulge
520 in a spot of body-snatching. It could be a useful technique for on-line
521 tutorials, too, where you take a user through a serious of steps and
522 don't want them to diverge from the lesson. Here, you can examine the events
523 coming from buttons and windows, and if acceptable, pass them through to
524 the original event handler. Use PushEventHandler/PopEventHandler
525 to form a chain of event handlers, where each handler processes a different
526 range of events independently from the other handlers.
527
528
529
530 @section overview_eventhandling_winid Window Identifiers
531
532 Window identifiers are integers, and are used to
533 uniquely determine window identity in the event system (though you can use it
534 for other purposes). In fact, identifiers do not need to be unique
535 across your entire application as long they are unique within the
536 particular context you're interested in, such as a frame and its children. You
537 may use the @c wxID_OK identifier, for example, on any number of dialogs
538 as long as you don't have several within the same dialog.
539
540 If you pass @c wxID_ANY to a window constructor, an identifier will be
541 generated for you automatically by wxWidgets. This is useful when you don't
542 care about the exact identifier either because you're not going to process the
543 events from the control being created or because you process the events
544 from all controls in one place (in which case you should specify @c wxID_ANY
545 in the event table or wxEvtHandler::Connect call
546 as well). The automatically generated identifiers are always negative and so
547 will never conflict with the user-specified identifiers which must be always
548 positive.
549
550 See @ref page_stdevtid for the list of standard identifiers available.
551 You can use wxID_HIGHEST to determine the number above which it is safe to
552 define your own identifiers. Or, you can use identifiers below wxID_LOWEST.
553 Finally, you can allocate identifiers dynamically using wxNewId() function too.
554 If you use wxNewId() consistently in your application, you can be sure that
555 your identifiers don't conflict accidentally.
556
557
558 @section overview_eventhandling_custom Custom Event Summary
559
560 @subsection overview_eventhandling_custom_general General approach
561
562 Since version 2.2.x of wxWidgets, each event type is identified by an ID
563 given to the event type @e at runtime that makes it possible to add
564 new event types to the library or application without risking ID clashes
565 (two different event types mistakingly getting the same event ID).
566 This event type ID is stored in a struct of type <b>const wxEventType</b>.
567
568 In order to define a new event type, there are principally two choices.
569 One is to define an entirely new event class (typically deriving from
570 wxEvent or wxCommandEvent).
571
572 The other is to use the existing event classes and give them a new event
573 type. You'll have to define and declare a new event type either way
574 using the following macros:
575
576 @code
577 // in the header of the source file
578 extern const wxEventType wxEVT_YOUR_EVENT_NAME;
579
580 // in the implementation
581 DEFINE_EVENT_TYPE(wxEVT_YOUR_EVENT_NAME)
582 @endcode
583
584 See also the @ref page_samples_event for an example of code
585 defining and working with the custom event types.
586
587
588 @subsection overview_eventhandling_custom_existing Using Existing Event Classes
589
590 If you just want to use a wxCommandEvent with a new event type, use
591 one of the generic event table macros listed below, without having to define a
592 new event class yourself. This also has the advantage that you won't have to define a
593 new wxEvent::Clone() method for posting events between threads etc.
594
595 Example:
596
597 @code
598 extern const wxEventType wxEVT_MY_EVENT;
599 DEFINE_EVENT_TYPE(wxEVT_MY_EVENT)
600
601 // user code intercepting the event
602
603 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
604 EVT_MENU (wxID_EXIT, MyFrame::OnExit)
605 // ....
606 EVT_COMMAND (ID_MY_WINDOW, wxEVT_MY_EVENT, MyFrame::OnMyEvent)
607 END_EVENT_TABLE()
608
609 void MyFrame::OnMyEvent( wxCommandEvent& event )
610 {
611 // do something
612 wxString text = event.GetText();
613 }
614
615
616 // user code sending the event
617
618 void MyWindow::SendEvent()
619 {
620 wxCommandEvent event( wxEVT_MY_EVENT, GetId() );
621 event.SetEventObject( this );
622
623 // Give it some contents
624 event.SetText( wxT("Hallo") );
625
626 // Send it
627 GetEventHandler()->ProcessEvent( event );
628 }
629 @endcode
630
631
632 @subsection overview_eventhandling_custom_generic Generic Event Table Macros
633
634 @beginTable
635 @row2col{EVT_CUSTOM(event\, id\, func),
636 Allows you to add a custom event table
637 entry by specifying the event identifier (such as wxEVT_SIZE),
638 the window identifier, and a member function to call.}
639 @row2col{EVT_CUSTOM_RANGE(event\, id1\, id2\, func),
640 The same as EVT_CUSTOM, but responds to a range of window identifiers.}
641 @row2col{EVT_COMMAND(id\, event\, func),
642 The same as EVT_CUSTOM, but expects a member function with a
643 wxCommandEvent argument.}
644 @row2col{EVT_COMMAND_RANGE(id1\, id2\, event\, func),
645 The same as EVT_CUSTOM_RANGE, but
646 expects a member function with a wxCommandEvent argument.}
647 @row2col{EVT_NOTIFY(event\, id\, func),
648 The same as EVT_CUSTOM, but
649 expects a member function with a wxNotifyEvent argument.}
650 @row2col{EVT_NOTIFY_RANGE(event\, id1\, id2\, func),
651 The same as EVT_CUSTOM_RANGE, but
652 expects a member function with a wxNotifyEvent argument.}
653 @endTable
654
655
656 @subsection overview_eventhandling_custom_ownclass Defining Your Own Event Class
657
658 Under certain circumstances, you must define your own event
659 class e.g., for sending more complex data from one place to another. Apart
660 from defining your event class, you will also need to define your own
661 event table macro (which is quite long). Watch out to put in enough
662 casts to the inherited event function. Here is an example:
663
664 @code
665 // code defining event
666
667 class wxPlotEvent: public wxNotifyEvent
668 {
669 public:
670 wxPlotEvent( wxEventType commandType = wxEVT_NULL, int id = 0 );
671
672 // accessors
673 wxPlotCurve *GetCurve()
674 { return m_curve; }
675
676 // required for sending with wxPostEvent()
677 virtual wxEvent *Clone() const;
678
679 private:
680 wxPlotCurve *m_curve;
681 };
682
683 extern const wxEventType wxEVT_PLOT_ACTION;
684 typedef void (wxEvtHandler::*wxPlotEventFunction)(wxPlotEvent&);
685
686 #define wxPlotEventHandler(func) \
687 (wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxPlotEventFunction, &func)
688 #define EVT_PLOT(id, fn) \
689 wx__DECLARE_EVT1(wxEVT_PLOT_ACTION, id, wxPlotEventHandler(fn))
690
691
692 // code implementing the event type and the event class
693
694 DEFINE_EVENT_TYPE( wxEVT_PLOT_ACTION )
695
696 wxPlotEvent::wxPlotEvent( ... )
697 {
698 ...
699 }
700
701
702 // user code intercepting the event
703
704 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
705 EVT_PLOT (ID_MY_WINDOW, MyFrame::OnPlot)
706 END_EVENT_TABLE()
707
708 void MyFrame::OnPlot( wxPlotEvent &event )
709 {
710 wxPlotCurve *curve = event.GetCurve();
711 }
712
713
714 // user code sending the event
715
716 void MyWindow::SendEvent()
717 {
718 wxPlotEvent event( wxEVT_PLOT_ACTION, GetId() );
719 event.SetEventObject( this );
720 event.SetCurve( m_curve );
721 GetEventHandler()->ProcessEvent( event );
722 }
723 @endcode
724
725
726 @section overview_eventhandling_macros Event Handling Summary
727
728 For the full list of event classes, please see the
729 @ref group_class_events "event classes group page".
730
731
732 @todo For all controls, state clearly when calling a member function results in
733 an event being generated and when it doesn't (possibly updating also the
734 'Events generated by the user versus programmatically-generated events'
735 paragraph of the 'Event Handling Overview' with the list of the functions
736 that break the rule).
737
738 */
739