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