eventhandling.h 36 KB

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