Define _CRT_NONSTDC_NO_WARNINGS for zlib compilation with MSVC.
[wxWidgets.git] / docs / doxygen / overviews / eventhandling.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: eventhandling.h
3 // Purpose: topic overview
4 // Author: wxWidgets team
5 // Licence: wxWindows licence
6 /////////////////////////////////////////////////////////////////////////////
7
8 /**
9
10 @page overview_events Events and Event Handling
11
12 @tableofcontents
13
14 Like with all the other GUI frameworks, the control of flow in wxWidgets
15 applications is event-based: the program normally performs most of its actions
16 in response to the events generated by the user. These events can be triggered
17 by using the input devices (such as keyboard, mouse, joystick) directly or,
18 more commonly, by a standard control which synthesizes such input events into
19 higher level events: for example, a wxButton can generate a click event when
20 the user presses the left mouse button on it and then releases it without
21 pressing @c Esc in the meanwhile. There are also events which don't directly
22 correspond to the user actions, such as wxTimerEvent or wxSocketEvent.
23
24 But in all cases wxWidgets represents these events in a uniform way and allows
25 you to handle them in the same way wherever they originate from. And while the
26 events are normally generated by wxWidgets itself, you can also do this, which
27 is especially useful when using custom events (see @ref overview_events_custom).
28
29 To be more precise, each event is described by:
30 - <em>Event type</em>: this is simply a value of type wxEventType which
31 uniquely identifies the type of the event. For example, clicking on a button,
32 selecting an item from a list box and pressing a key on the keyboard all
33 generate events with different event types.
34 - <em>Event class</em> carried by the event: each event has some information
35 associated with it and this data is represented by an object of a class
36 derived from wxEvent. Events of different types can use the same event class,
37 for example both button click and listbox selection events use wxCommandEvent
38 class (as do all the other simple control events), but the key press event
39 uses wxKeyEvent as the information associated with it is different.
40 - <em>Event source</em>: wxEvent stores the object which generated the event
41 and, for windows, its identifier (see @ref overview_events_winid). As it is
42 common to have more than one object generating events of the same type (e.g. a
43 typical window contains several buttons, all generating the same button click
44 event), checking the event source object or its id allows to distinguish
45 between them.
46
47 @see wxEvtHandler, wxWindow, wxEvent
48
49
50
51 @section overview_events_eventhandling Event Handling
52
53 There are two principal ways to handle events in wxWidgets. One of them uses
54 <em>event table</em> macros and allows you to define the binding between events
55 and their handlers only statically, i.e., during program compilation. The other
56 one uses wxEvtHandler::Bind<>() call and can be used to bind and
57 unbind, the handlers dynamically, i.e. during run-time depending on some
58 conditions. It also allows the direct binding of events to:
59 @li A handler method in another object.
60 @li An ordinary function like a static method or a global function.
61 @li An arbitrary functor like boost::function<>.
62
63 The static event tables can only handle events in the object where they are
64 defined so using Bind<>() is more flexible than using the event tables. On the
65 other hand, event tables are more succinct and centralize all event handler
66 bindings in one place. You can either choose a single approach that you find
67 preferable or freely combine both methods in your program in different classes
68 or even in one and the same class, although this is probably sufficiently
69 confusing to be a bad idea.
70
71 Also notice that most of the existing wxWidgets tutorials and discussions use
72 the event tables because they historically preceded the apparition of dynamic
73 event handling in wxWidgets. But this absolutely doesn't mean that using the
74 event tables is the preferred way: handling events dynamically is better in
75 several aspects and you should strongly consider doing it if you are just
76 starting with wxWidgets. On the other hand, you still need to know about the
77 event tables if only because you are going to see them in many samples and
78 examples.
79
80 So before you make the choice between static event tables and dynamically
81 connecting the event handlers, let us discuss these two ways in more detail. In
82 the next section we provide a short introduction to handling the events using
83 the event tables. Please see @ref overview_events_bind for the discussion of
84 Bind<>().
85
86 @subsection overview_events_eventtables Event Handling with Event Tables
87
88 To use an <em>event table</em> you must first decide in which class you wish to
89 handle the events. The only requirement imposed by wxWidgets is that this class
90 must derive from wxEvtHandler and so, considering that wxWindow derives from
91 it, any classes representing windows can handle events. Simple events such as
92 menu commands are usually processed at the level of a top-level window
93 containing the menu, so let's suppose that you need to handle some events in @c
94 MyFrame class deriving from wxFrame.
95
96 First define one or more <em>event handlers</em>. They
97 are just simple methods of the class that take as a parameter a
98 reference to an object of a wxEvent-derived class and have no return value (any
99 return information is passed via the argument, which is why it is non-const).
100 You also need to insert a macro
101
102 @code
103 wxDECLARE_EVENT_TABLE()
104 @endcode
105
106 somewhere in the class declaration. It doesn't matter where it appears but
107 it's customary to put it at the end because the macro changes the access
108 type internally so it's safest if nothing follows it. The
109 full class declaration might look like this:
110
111 @code
112 class MyFrame : public wxFrame
113 {
114 public:
115 MyFrame(...) : wxFrame(...) { }
116
117 ...
118
119 protected:
120 int m_whatever;
121
122 private:
123 // Notice that as the event handlers normally are not called from outside
124 // the class, they normally are private. In particular they don't need
125 // to be public.
126 void OnExit(wxCommandEvent& event);
127 void OnButton1(wxCommandEvent& event);
128 void OnSize(wxSizeEvent& event);
129
130 // it's common to call the event handlers OnSomething() but there is no
131 // obligation to do that; this one is an event handler too:
132 void DoTest(wxCommandEvent& event);
133
134 wxDECLARE_EVENT_TABLE()
135 };
136 @endcode
137
138 Next the event table must be defined and, as with any definition, it must be
139 placed in an implementation file. The event table tells wxWidgets how to map
140 events to member functions and in our example it could look like this:
141
142 @code
143 wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
144 EVT_MENU(wxID_EXIT, MyFrame::OnExit)
145 EVT_MENU(DO_TEST, MyFrame::DoTest)
146 EVT_SIZE(MyFrame::OnSize)
147 EVT_BUTTON(BUTTON1, MyFrame::OnButton1)
148 wxEND_EVENT_TABLE()
149 @endcode
150
151 Notice that you must mention a method you want to use for the event handling in
152 the event table definition; just defining it in MyFrame class is @e not enough.
153
154 Let us now look at the details of this definition: the first line means that we
155 are defining the event table for MyFrame class and that its base class is
156 wxFrame, so events not processed by MyFrame will, by default, be handled by
157 wxFrame. The next four lines define bindings of individual events to their
158 handlers: the first two of them map menu commands from the items with the
159 identifiers specified as the first macro parameter to two different member
160 functions. In the next one, @c EVT_SIZE means that any changes in the size of
161 the frame will result in calling OnSize() method. Note that this macro doesn't
162 need a window identifier, since normally you are only interested in the current
163 window's size events.
164
165 The @c EVT_BUTTON macro demonstrates that the originating event does not have to
166 come from the window class implementing the event table -- if the event source
167 is a button within a panel within a frame, this will still work, because event
168 tables are searched up through the hierarchy of windows for the command events.
169 (But only command events, so you can't catch mouse move events in a child
170 control in the parent window in the same way because wxMouseEvent doesn't
171 derive from wxCommandEvent. See below for how you can do it.) In this case, the
172 button's event table will be searched, then the parent panel's, then the
173 frame's.
174
175 Finally, you need to implement the event handlers. As mentioned before, all
176 event handlers take a wxEvent-derived argument whose exact class differs
177 according to the type of event and the class of the originating window. For
178 size events, wxSizeEvent is used. For menu commands and most control commands
179 (such as button presses), wxCommandEvent is used. When controls get more
180 complicated, more specific wxCommandEvent-derived event classes providing
181 additional control-specific information can be used, such as wxTreeEvent for
182 events from wxTreeCtrl windows.
183
184 In the simplest possible case an event handler may not use the @c event
185 parameter at all. For example,
186
187 @code
188 void MyFrame::OnExit(wxCommandEvent& WXUNUSED(event))
189 {
190 // when the user selects "Exit" from the menu we should close
191 Close(true);
192 }
193 @endcode
194
195 In other cases you may need some information carried by the @c event argument,
196 as in:
197
198 @code
199 void MyFrame::OnSize(wxSizeEvent& event)
200 {
201 wxSize size = event.GetSize();
202
203 ... update the frame using the new size ...
204 }
205 @endcode
206
207 You will find the details about the event table macros and the corresponding
208 wxEvent-derived classes in the discussion of each control generating these
209 events.
210
211
212 @subsection overview_events_bind Dynamic Event Handling
213
214 @see @ref overview_cpp_rtti_disabled
215
216 The possibilities of handling events in this way are rather different.
217 Let us start by looking at the syntax: the first obvious difference is that you
218 need not use wxDECLARE_EVENT_TABLE() nor wxBEGIN_EVENT_TABLE() and the
219 associated macros. Instead, in any place in your code, but usually in
220 the code of the class defining the handler itself (and definitely not in the
221 global scope as with the event tables), call its Bind<>() method like this:
222
223 @code
224 MyFrame::MyFrame(...)
225 {
226 Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExit, this, wxID_EXIT);
227 }
228 @endcode
229
230 Note that @c this pointer must be specified here.
231
232 Now let us describe the semantic differences:
233 <ul>
234 <li>
235 Event handlers can be bound at any moment. For example, it's possible
236 to do some initialization first and only bind the handlers if and when
237 it succeeds. This can avoid the need to test that the object was properly
238 initialized in the event handlers themselves. With Bind<>() they
239 simply won't be called if it wasn't correctly initialized.
240 </li>
241
242 <li>
243 As a slight extension of the above, the handlers can also be unbound at
244 any time with Unbind<>() (and maybe rebound later). Of course,
245 it's also possible to emulate this behaviour with the classic
246 static (i.e., bound via event tables) handlers by using an internal
247 flag indicating whether the handler is currently enabled and returning
248 from it if it isn't, but using dynamically bind handlers requires
249 less code and is also usually more clear.
250 </li>
251
252 <li>
253 Almost last but very, very far from least is the increased flexibility
254 which allows to bind an event to:
255 @li A method in another object.
256 @li An ordinary function like a static method or a global function.
257 @li An arbitrary functor like boost::function<>.
258
259 This is impossible to do with the event tables because it is not
260 possible to specify these handlers to dispatch the event to, so it
261 necessarily needs to be sent to the same object which generated the
262 event. Not so with Bind<>() which can be used to specify these handlers
263 which will handle the event. To give a quick example, a common question
264 is how to receive the mouse movement events happening when the mouse is
265 in one of the frame children in the frame itself. Doing it in a naive
266 way doesn't work:
267 <ul>
268 <li>
269 A @c EVT_LEAVE_WINDOW(MyFrame::OnMouseLeave) line in the frame
270 event table has no effect as mouse move (including entering and
271 leaving) events are not propagated up to the parent window
272 (at least not by default).
273 </li>
274
275 <li>
276 Putting the same line in a child event table will crash during
277 run-time because the MyFrame method will be called on a wrong
278 object -- it's easy to convince oneself that the only object
279 that can be used here is the pointer to the child, as
280 wxWidgets has nothing else. But calling a frame method with the
281 child window pointer instead of the pointer to the frame is, of
282 course, disastrous.
283 </li>
284 </ul>
285
286 However writing
287 @code
288 MyFrame::MyFrame(...)
289 {
290 m_child->Bind(wxEVT_LEAVE_WINDOW, &MyFrame::OnMouseLeave, this);
291 }
292 @endcode
293 will work exactly as expected. Note that you can get the object that
294 generated the event -- and that is not the same as the frame -- via
295 wxEvent::GetEventObject() method of @c event argument passed to the
296 event handler.
297 </li>
298
299 <li>
300 Really last point is the consequence of the previous one: because of
301 increased flexibility of Bind(), it is also safer as it is impossible
302 to accidentally use a method of another class. Instead of run-time
303 crashes you will get compilation errors in this case when using Bind().
304 </li>
305 </ul>
306
307 Let us now look at more examples of how to use different event handlers using
308 the two overloads of Bind() function: first one for the object methods and the
309 other one for arbitrary functors (callable objects, including simple functions):
310
311 In addition to using a method of the object generating the event itself, you
312 can use a method from a completely different object as an event handler:
313
314 @code
315 void MyFrameHandler::OnFrameExit( wxCommandEvent & )
316 {
317 // Do something useful.
318 }
319
320 MyFrameHandler myFrameHandler;
321
322 MyFrame::MyFrame()
323 {
324 Bind( wxEVT_COMMAND_MENU_SELECTED, &MyFrameHandler::OnFrameExit,
325 &myFrameHandler, wxID_EXIT );
326 }
327 @endcode
328
329 Note that @c MyFrameHandler doesn't need to derive from wxEvtHandler. But
330 keep in mind that then the lifetime of @c myFrameHandler must be greater than
331 that of @c MyFrame object -- or at least it needs to be unbound before being
332 destroyed.
333
334
335 To use an ordinary function or a static method as an event handler you would
336 write something like this:
337
338 @code
339 void HandleExit( wxCommandEvent & )
340 {
341 // Do something useful
342 }
343
344 MyFrame::MyFrame()
345 {
346 Bind( wxEVT_COMMAND_MENU_SELECTED, &HandleExit, wxID_EXIT );
347 }
348 @endcode
349
350 And finally you can bind to an arbitrary functor and use it as an event
351 handler:
352
353 @code
354
355 struct MyFunctor
356 {
357 void operator()( wxCommandEvent & )
358 {
359 // Do something useful
360 }
361 };
362
363 MyFunctor myFunctor;
364
365 MyFrame::MyFrame()
366 {
367 Bind( wxEVT_COMMAND_MENU_SELECTED, myFunctor, wxID_EXIT );
368 }
369 @endcode
370
371 A common example of a functor is boost::function<>:
372
373 @code
374 using namespace boost;
375
376 void MyHandler::OnExit( wxCommandEvent & )
377 {
378 // Do something useful
379 }
380
381 MyHandler myHandler;
382
383 MyFrame::MyFrame()
384 {
385 function< void ( wxCommandEvent & ) > exitHandler( bind( &MyHandler::OnExit, &myHandler, _1 ));
386
387 Bind( wxEVT_COMMAND_MENU_SELECTED, exitHandler, wxID_EXIT );
388 }
389 @endcode
390
391
392 With the aid of boost::bind<>() you can even use methods or functions which
393 don't quite have the correct signature:
394
395 @code
396 void MyHandler::OnExit( int exitCode, wxCommandEvent &, wxString goodByeMessage )
397 {
398 // Do something useful
399 }
400
401 MyHandler myHandler;
402
403 MyFrame::MyFrame()
404 {
405 function< void ( wxCommandEvent & ) > exitHandler(
406 bind( &MyHandler::OnExit, &myHandler, EXIT_FAILURE, _1, "Bye" ));
407
408 Bind( wxEVT_COMMAND_MENU_SELECTED, exitHandler, wxID_EXIT );
409 }
410 @endcode
411
412
413 To summarize, using Bind<>() requires slightly more typing but is much more
414 flexible than using static event tables so don't hesitate to use it when you
415 need this extra power. On the other hand, event tables are still perfectly fine
416 in simple situations where this extra flexibility is not needed.
417
418
419 @section overview_events_processing How Events are Processed
420
421 The previous sections explain how to define event handlers but don't address
422 the question of how exactly wxWidgets finds the handler to call for the
423 given event. This section describes the algorithm used in detail. Notice that
424 you may want to run the @ref page_samples_event while reading this section and
425 look at its code and the output when the button which can be used to test the
426 event handlers execution order is clicked to understand it better.
427
428 When an event is received from the windowing system, wxWidgets calls
429 wxEvtHandler::ProcessEvent() on the first event handler object belonging to the
430 window generating the event. The normal order of event table searching by
431 ProcessEvent() is as follows, with the event processing stopping as soon as a
432 handler is found (unless the handler calls wxEvent::Skip() in which case it
433 doesn't count as having handled the event and the search continues):
434 <ol>
435 <li value="0">
436 Before anything else happens, wxApp::FilterEvent() is called. If it returns
437 anything but -1 (default), the event handling stops immediately.
438 </li>
439
440 <li value="1">
441 If this event handler is disabled via a call to
442 wxEvtHandler::SetEvtHandlerEnabled() the next three steps are skipped and
443 the event handler resumes at step (5).
444 </li>
445
446 <li value="2">
447 If the object is a wxWindow and has an associated validator, wxValidator
448 gets a chance to process the event.
449 </li>
450
451 <li value="3">
452 The list of dynamically bound event handlers, i.e., those for which
453 Bind<>() was called, is consulted. Notice that this is done before
454 checking the static event table entries, so if both a dynamic and a static
455 event handler match the same event, the static one is never going to be
456 used unless wxEvent::Skip() is called in the dynamic one.
457 </li>
458
459 <li value="4">
460 The event table containing all the handlers defined using the event table
461 macros in this class and its base classes is examined. Notice that this
462 means that any event handler defined in a base class will be executed at
463 this step.
464 </li>
465
466 <li value="5">
467 The event is passed to the next event handler, if any, in the event handler
468 chain, i.e., the steps (1) to (4) are done for it. Usually there is no next
469 event handler so the control passes to the next step but see @ref
470 overview_events_nexthandler for how the next handler may be defined.
471 </li>
472
473 <li value="6">
474 If the object is a wxWindow and the event is set to propagate (by default
475 only wxCommandEvent-derived events are set to propagate), then the
476 processing restarts from the step (1) (and excluding the step (7)) for the
477 parent window. If this object is not a window but the next handler exists,
478 the event is passed to its parent if it is a window. This ensures that in a
479 common case of (possibly several) non-window event handlers pushed on top
480 of a window, the event eventually reaches the window parent.
481 </li>
482
483 <li value="7">
484 Finally, i.e., if the event is still not processed, the wxApp object itself
485 (which derives from wxEvtHandler) gets a last chance to process it.
486 </li>
487 </ol>
488
489 <em>Please pay close attention to step 6!</em> People often overlook or get
490 confused by this powerful feature of the wxWidgets event processing system. The
491 details of event propagation up the window hierarchy are described in the
492 next section.
493
494 Also please notice that there are additional steps in the event handling for
495 the windows-making part of wxWidgets document-view framework, i.e.,
496 wxDocParentFrame, wxDocChildFrame and their MDI equivalents wxDocMDIParentFrame
497 and wxDocMDIChildFrame. The parent frame classes modify step (2) above to
498 send the events received by them to wxDocManager object first. This object, in
499 turn, sends the event to the current view and the view itself lets its
500 associated document process the event first. The child frame classes send
501 the event directly to the associated view which still forwards it to its
502 document object. Notice that to avoid remembering the exact order in which the
503 events are processed in the document-view frame, the simplest, and recommended,
504 solution is to only handle the events at the view classes level, and not in the
505 document or document manager classes
506
507
508 @subsection overview_events_propagation How Events Propagate Upwards
509
510 As mentioned above, the events of the classes deriving from wxCommandEvent are
511 propagated by default to the parent window if they are not processed in this
512 window itself. But although by default only the command events are propagated
513 like this, other events can be propagated as well because the event handling
514 code uses wxEvent::ShouldPropagate() to check whether an event should be
515 propagated. It is also possible to propagate the event only a limited number of
516 times and not until it is processed (or a top level parent window is reached).
517
518 Finally, there is another additional complication (which, in fact, simplifies
519 life of wxWidgets programmers significantly): when propagating the command
520 events up to the parent window, the event propagation stops when it
521 reaches the parent dialog, if any. This means that you don't risk getting
522 unexpected events from the dialog controls (which might be left unprocessed by
523 the dialog itself because it doesn't care about them) when a modal dialog is
524 popped up. The events do propagate beyond the frames, however. The rationale
525 for this choice is that there are only a few frames in a typical application
526 and their parent-child relation are well understood by the programmer while it
527 may be difficult, if not impossible, to track down all the dialogs that
528 may be popped up in a complex program (remember that some are created
529 automatically by wxWidgets). If you need to specify a different behaviour for
530 some reason, you can use <tt>wxWindow::SetExtraStyle(wxWS_EX_BLOCK_EVENTS)</tt>
531 explicitly to prevent the events from being propagated beyond the given window
532 or unset this flag for the dialogs that have it on by default.
533
534 Typically events that deal with a window as a window (size, motion,
535 paint, mouse, keyboard, etc.) are sent only to the window. Events
536 that have a higher level of meaning or are generated by the window
537 itself (button click, menu select, tree expand, etc.) are command
538 events and are sent up to the parent to see if it is interested in the event.
539 More precisely, as said above, all event classes @b not deriving from wxCommandEvent
540 (see the wxEvent inheritance map) do @b not propagate upward.
541
542 In some cases, it might be desired by the programmer to get a certain number
543 of system events in a parent window, for example all key events sent to, but not
544 used by, the native controls in a dialog. In this case, a special event handler
545 will have to be written that will override ProcessEvent() in order to pass
546 all events (or any selection of them) to the parent window.
547
548
549 @subsection overview_events_nexthandler Event Handlers Chain
550
551 The step 4 of the event propagation algorithm checks for the next handler in
552 the event handler chain. This chain can be formed using
553 wxEvtHandler::SetNextHandler():
554 @image html overview_events_chain.png
555 (referring to the image, if @c A->ProcessEvent is called and it doesn't handle
556 the event, @c B->ProcessEvent will be called and so on...).
557
558 Additionally, in the case of wxWindow you can build a stack (implemented using
559 wxEvtHandler double-linked list) using wxWindow::PushEventHandler():
560 @image html overview_events_winstack.png
561 (referring to the image, if @c W->ProcessEvent is called, it immediately calls
562 @c A->ProcessEvent; if nor @c A nor @c B handle the event, then the wxWindow
563 itself is used -- i.e. the dynamically bind event handlers and static event
564 table entries of wxWindow are looked as the last possibility, after all pushed
565 event handlers were tested).
566
567 By default the chain is empty, i.e. there is no next handler.
568
569
570 @section overview_events_custom Custom Event Summary
571
572 @subsection overview_events_custom_general General approach
573
574 As each event is uniquely defined by its event type, defining a custom event
575 starts with defining a new event type for it. This is done using
576 wxDEFINE_EVENT() macro. As an event type is a variable, it can also be
577 declared using wxDECLARE_EVENT() if necessary.
578
579 The next thing to do is to decide whether you need to define a custom event
580 class for events of this type or if you can reuse an existing class, typically
581 either wxEvent (which doesn't provide any extra information) or wxCommandEvent
582 (which contains several extra fields and also propagates upwards by default).
583 Both strategies are described in details below. See also the @ref
584 page_samples_event for a complete example of code defining and working with the
585 custom event types.
586
587 Finally, you will need to generate and post your custom events.
588 Generation is as simple as instancing your custom event class and initializing
589 its internal fields.
590 For posting events to a certain event handler there are two possibilities:
591 using wxEvtHandler::AddPendingEvent or using wxEvtHandler::QueueEvent.
592 Basically you will need to use the latter when doing inter-thread communication;
593 when you use only the main thread you can also safely use the former.
594 Last, note that there are also two simple global wrapper functions associated
595 to the two wxEvtHandler mentioned functions: wxPostEvent() and wxQueueEvent().
596
597
598 @subsection overview_events_custom_existing Using Existing Event Classes
599
600 If you just want to use a wxCommandEvent with a new event type, use one of the
601 generic event table macros listed below, without having to define a new event
602 class yourself.
603
604 Example:
605
606 @code
607 // this is typically in a header: it just declares MY_EVENT event type
608 wxDECLARE_EVENT(MY_EVENT, wxCommandEvent);
609
610 // this is a definition so can't be in a header
611 wxDEFINE_EVENT(MY_EVENT, wxCommandEvent);
612
613 // example of code handling the event with event tables
614 wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
615 EVT_MENU (wxID_EXIT, MyFrame::OnExit)
616 ...
617 EVT_COMMAND (ID_MY_WINDOW, MY_EVENT, MyFrame::OnMyEvent)
618 wxEND_EVENT_TABLE()
619
620 void MyFrame::OnMyEvent(wxCommandEvent& event)
621 {
622 // do something
623 wxString text = event.GetString();
624 }
625
626 // example of code handling the event with Bind<>():
627 MyFrame::MyFrame()
628 {
629 Bind(MY_EVENT, &MyFrame::OnMyEvent, this, ID_MY_WINDOW);
630 }
631
632 // example of code generating the event
633 void MyWindow::SendEvent()
634 {
635 wxCommandEvent event(MY_EVENT, GetId());
636 event.SetEventObject(this);
637
638 // Give it some contents
639 event.SetString("Hello");
640
641 // Do send it
642 ProcessWindowEvent(event);
643 }
644 @endcode
645
646
647 @subsection overview_events_custom_ownclass Defining Your Own Event Class
648
649 Under certain circumstances, you must define your own event class e.g., for
650 sending more complex data from one place to another. Apart from defining your
651 event class, you also need to define your own event table macro if you want to
652 use event tables for handling events of this type.
653
654 Here is an example:
655
656 @code
657 // define a new event class
658 class MyPlotEvent: public wxEvent
659 {
660 public:
661 MyPlotEvent(wxEventType eventType, int winid, const wxPoint& pos)
662 : wxEvent(winid, eventType),
663 m_pos(pos)
664 {
665 }
666
667 // accessors
668 wxPoint GetPoint() const { return m_pos; }
669
670 // implement the base class pure virtual
671 virtual wxEvent *Clone() const { return new MyPlotEvent(*this); }
672
673 private:
674 const wxPoint m_pos;
675 };
676
677 // we define a single MY_PLOT_CLICKED event type associated with the class
678 // above but typically you are going to have more than one event type, e.g. you
679 // could also have MY_PLOT_ZOOMED or MY_PLOT_PANNED &c -- in which case you
680 // would just add more similar lines here
681 wxDEFINE_EVENT(MY_PLOT_CLICKED, MyPlotEvent);
682
683
684 // if you want to support old compilers you need to use some ugly macros:
685 typedef void (wxEvtHandler::*MyPlotEventFunction)(MyPlotEvent&);
686 #define MyPlotEventHandler(func) wxEVENT_HANDLER_CAST(MyPlotEventFunction, func)
687
688 // if your code is only built using reasonably modern compilers, you could just
689 // do this instead:
690 #define MyPlotEventHandler(func) (&func)
691
692 // finally define a macro for creating the event table entries for the new
693 // event type
694 //
695 // remember that you don't need this at all if you only use Bind<>() and that
696 // you can replace MyPlotEventHandler(func) with just &func unless you use a
697 // really old compiler
698 #define MY_EVT_PLOT_CLICK(id, func) \
699 wx__DECLARE_EVT1(MY_PLOT_CLICKED, id, MyPlotEventHandler(func))
700
701
702 // example of code handling the event (you will use one of these methods, not
703 // both, of course):
704 wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
705 EVT_PLOT(ID_MY_WINDOW, MyFrame::OnPlot)
706 wxEND_EVENT_TABLE()
707
708 MyFrame::MyFrame()
709 {
710 Bind(MY_PLOT_CLICKED, &MyFrame::OnPlot, this, ID_MY_WINDOW);
711 }
712
713 void MyFrame::OnPlot(MyPlotEvent& event)
714 {
715 ... do something with event.GetPoint() ...
716 }
717
718
719 // example of code generating the event:
720 void MyWindow::SendEvent()
721 {
722 MyPlotEvent event(MY_PLOT_CLICKED, GetId(), wxPoint(...));
723 event.SetEventObject(this);
724 ProcessWindowEvent(event);
725 }
726 @endcode
727
728
729
730 @section overview_events_misc Miscellaneous Notes
731
732 @subsection overview_events_virtual Event Handlers vs Virtual Methods
733
734 It may be noted that wxWidgets' event processing system implements something
735 close to virtual methods in normal C++ in spirit: both of these mechanisms
736 allow you to alter the behaviour of the base class by defining the event handling
737 functions in the derived classes.
738
739 There is however an important difference between the two mechanisms when you
740 want to invoke the default behaviour, as implemented by the base class, from a
741 derived class handler. With the virtual functions, you need to call the base
742 class function directly and you can do it either in the beginning of the
743 derived class handler function (to post-process the event) or at its end (to
744 pre-process the event). With the event handlers, you only have the option of
745 pre-processing the events and in order to still let the default behaviour
746 happen you must call wxEvent::Skip() and @em not call the base class event
747 handler directly. In fact, the event handler probably doesn't even exist in the
748 base class as the default behaviour is often implemented in platform-specific
749 code by the underlying toolkit or OS itself. But even if it does exist at
750 wxWidgets level, it should never be called directly as the event handlers are
751 not part of wxWidgets API and should never be called directly.
752
753
754
755 @subsection overview_events_prog User Generated Events vs Programmatically Generated Events
756
757 While generically wxEvents can be generated both by user
758 actions (e.g., resize of a wxWindow) and by calls to functions
759 (e.g., wxWindow::SetSize), wxWidgets controls normally send wxCommandEvent-derived
760 events only for the user-generated events. The only @b exceptions to this rule are:
761
762 @li wxNotebook::AddPage: No event-free alternatives
763 @li wxNotebook::AdvanceSelection: No event-free alternatives
764 @li wxNotebook::DeletePage: No event-free alternatives
765 @li wxNotebook::SetSelection: Use wxNotebook::ChangeSelection instead, as
766 wxNotebook::SetSelection is deprecated
767 @li wxTreeCtrl::Delete: No event-free alternatives
768 @li wxTreeCtrl::DeleteAllItems: No event-free alternatives
769 @li wxTreeCtrl::EditLabel: No event-free alternatives
770 @li All wxTextCtrl methods
771
772 wxTextCtrl::ChangeValue can be used instead of wxTextCtrl::SetValue but the other
773 functions, such as wxTextCtrl::Replace or wxTextCtrl::WriteText don't have event-free
774 equivalents.
775
776
777
778 @subsection overview_events_pluggable Pluggable Event Handlers
779
780 <em>TODO: Probably deprecated, Bind() provides a better way to do this</em>
781
782 In fact, you don't have to derive a new class from a window class
783 if you don't want to. You can derive a new class from wxEvtHandler instead,
784 defining the appropriate event table, and then call wxWindow::SetEventHandler
785 (or, preferably, wxWindow::PushEventHandler) to make this
786 event handler the object that responds to events. This way, you can avoid
787 a lot of class derivation, and use instances of the same event handler class (but different
788 objects as the same event handler object shouldn't be used more than once) to
789 handle events from instances of different widget classes.
790
791 If you ever have to call a window's event handler
792 manually, use the GetEventHandler function to retrieve the window's event handler and use that
793 to call the member function. By default, GetEventHandler returns a pointer to the window itself
794 unless an application has redirected event handling using SetEventHandler or PushEventHandler.
795
796 One use of PushEventHandler is to temporarily or permanently change the
797 behaviour of the GUI. For example, you might want to invoke a dialog editor
798 in your application that changes aspects of dialog boxes. You can
799 grab all the input for an existing dialog box, and edit it 'in situ',
800 before restoring its behaviour to normal. So even if the application
801 has derived new classes to customize behaviour, your utility can indulge
802 in a spot of body-snatching. It could be a useful technique for on-line
803 tutorials, too, where you take a user through a serious of steps and
804 don't want them to diverge from the lesson. Here, you can examine the events
805 coming from buttons and windows, and if acceptable, pass them through to
806 the original event handler. Use PushEventHandler/PopEventHandler
807 to form a chain of event handlers, where each handler processes a different
808 range of events independently from the other handlers.
809
810
811
812 @subsection overview_events_winid Window Identifiers
813
814 Window identifiers are integers, and are used to
815 uniquely determine window identity in the event system (though you can use it
816 for other purposes). In fact, identifiers do not need to be unique
817 across your entire application as long they are unique within the
818 particular context you're interested in, such as a frame and its children. You
819 may use the @c wxID_OK identifier, for example, on any number of dialogs
820 as long as you don't have several within the same dialog.
821
822 If you pass @c wxID_ANY to a window constructor, an identifier will be
823 generated for you automatically by wxWidgets. This is useful when you don't
824 care about the exact identifier either because you're not going to process the
825 events from the control being created or because you process the events
826 from all controls in one place (in which case you should specify @c wxID_ANY
827 in the event table or wxEvtHandler::Bind call
828 as well). The automatically generated identifiers are always negative and so
829 will never conflict with the user-specified identifiers which must be always
830 positive.
831
832 See @ref page_stdevtid for the list of standard identifiers available.
833 You can use wxID_HIGHEST to determine the number above which it is safe to
834 define your own identifiers. Or, you can use identifiers below wxID_LOWEST.
835 Finally, you can allocate identifiers dynamically using wxNewId() function too.
836 If you use wxNewId() consistently in your application, you can be sure that
837 your identifiers don't conflict accidentally.
838
839
840 @subsection overview_events_custom_generic Generic Event Table Macros
841
842 @beginTable
843 @row2col{EVT_CUSTOM(event\, id\, func),
844 Allows you to add a custom event table
845 entry by specifying the event identifier (such as wxEVT_SIZE),
846 the window identifier, and a member function to call.}
847 @row2col{EVT_CUSTOM_RANGE(event\, id1\, id2\, func),
848 The same as EVT_CUSTOM, but responds to a range of window identifiers.}
849 @row2col{EVT_COMMAND(id\, event\, func),
850 The same as EVT_CUSTOM, but expects a member function with a
851 wxCommandEvent argument.}
852 @row2col{EVT_COMMAND_RANGE(id1\, id2\, event\, func),
853 The same as EVT_CUSTOM_RANGE, but
854 expects a member function with a wxCommandEvent argument.}
855 @row2col{EVT_NOTIFY(event\, id\, func),
856 The same as EVT_CUSTOM, but
857 expects a member function with a wxNotifyEvent argument.}
858 @row2col{EVT_NOTIFY_RANGE(event\, id1\, id2\, func),
859 The same as EVT_CUSTOM_RANGE, but
860 expects a member function with a wxNotifyEvent argument.}
861 @endTable
862
863
864
865 @subsection overview_events_list List of wxWidgets Events
866
867 For the full list of event classes, please see the
868 @ref group_class_events "event classes group page".
869
870
871 */