event.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: event.cpp
  3. // Purpose: wxWidgets sample demonstrating different event usage
  4. // Author: Vadim Zeitlin
  5. // Modified by:
  6. // Created: 31.01.01
  7. // Copyright: (c) 2001-2009 Vadim Zeitlin
  8. // Licence: wxWindows licence
  9. /////////////////////////////////////////////////////////////////////////////
  10. // ============================================================================
  11. // declarations
  12. // ============================================================================
  13. // ----------------------------------------------------------------------------
  14. // headers
  15. // ----------------------------------------------------------------------------
  16. // For compilers that support precompilation, includes "wx/wx.h".
  17. #include "wx/wxprec.h"
  18. #ifdef __BORLANDC__
  19. #pragma hdrstop
  20. #endif
  21. // for all others, include the necessary headers (this file is usually all you
  22. // need because it includes almost all "standard" wxWidgets headers)
  23. #ifndef WX_PRECOMP
  24. #include "wx/wx.h"
  25. #endif
  26. #ifndef wxHAS_IMAGES_IN_RESOURCES
  27. #include "../sample.xpm"
  28. #endif
  29. #include <wx/statline.h>
  30. #include <wx/log.h>
  31. // ----------------------------------------------------------------------------
  32. // event constants
  33. // ----------------------------------------------------------------------------
  34. // define a custom event type (we don't need a separate declaration here but
  35. // usually you would use a matching wxDECLARE_EVENT in a header)
  36. wxDEFINE_EVENT(wxEVT_MY_CUSTOM_COMMAND, wxCommandEvent);
  37. // it may also be convenient to define an event table macro for this event type
  38. #define EVT_MY_CUSTOM_COMMAND(id, fn) \
  39. DECLARE_EVENT_TABLE_ENTRY( \
  40. wxEVT_MY_CUSTOM_COMMAND, id, wxID_ANY, \
  41. wxCommandEventHandler(fn), \
  42. (wxObject *) NULL \
  43. ),
  44. // ----------------------------------------------------------------------------
  45. // private classes
  46. // ----------------------------------------------------------------------------
  47. // Define a new application type, each program should derive a class from wxApp
  48. class MyApp : public wxApp
  49. {
  50. public:
  51. // override base class virtuals
  52. // ----------------------------
  53. // this one is called on application startup and is a good place for the app
  54. // initialization (doing it here and not in the ctor allows to have an error
  55. // return: if OnInit() returns false, the application terminates)
  56. virtual bool OnInit();
  57. // these are regular event handlers used to highlight the events handling
  58. // order
  59. void OnClickDynamicHandlerApp(wxCommandEvent& event);
  60. void OnClickStaticHandlerApp(wxCommandEvent& event);
  61. // we override wxConsoleApp::FilterEvent used to highlight the events
  62. // handling order
  63. virtual int FilterEvent(wxEvent& event);
  64. private:
  65. wxDECLARE_EVENT_TABLE();
  66. };
  67. // Define a custom button used to highlight the events handling order
  68. class MyEvtTestButton : public wxButton
  69. {
  70. public:
  71. static long BUTTON_ID;
  72. MyEvtTestButton(wxWindow *parent, const wxString& label)
  73. : wxButton(parent, BUTTON_ID, label)
  74. {
  75. // Add a dynamic handler for this button event to button itself
  76. Connect(wxEVT_BUTTON,
  77. wxCommandEventHandler(MyEvtTestButton::OnClickDynamicHandler));
  78. }
  79. private:
  80. void OnClickDynamicHandler(wxCommandEvent& event)
  81. {
  82. wxLogMessage("Step 3 in \"How Events are Processed\":\n"
  83. "Button::ownDynamicHandler");
  84. event.Skip();
  85. }
  86. void OnClickStaticHandler(wxCommandEvent& event)
  87. {
  88. wxLogMessage("Step 4 in \"How Events are Processed\":\n"
  89. "Button::ownStaticHandler");
  90. event.Skip();
  91. }
  92. wxDECLARE_EVENT_TABLE();
  93. };
  94. long MyEvtTestButton::BUTTON_ID = wxNewId();
  95. // Define a new frame type: this is going to be our main frame
  96. class MyFrame : public wxFrame
  97. {
  98. public:
  99. // ctor(s)
  100. MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
  101. virtual ~MyFrame();
  102. void OnQuit(wxCommandEvent& event);
  103. void OnAbout(wxCommandEvent& event);
  104. #ifdef wxHAS_EVENT_BIND
  105. void OnBind(wxCommandEvent& event);
  106. #endif // wxHAS_EVENT_BIND
  107. void OnConnect(wxCommandEvent& event);
  108. void OnDynamic(wxCommandEvent& event);
  109. void OnPushEventHandler(wxCommandEvent& event);
  110. void OnPopEventHandler(wxCommandEvent& event);
  111. void OnTest(wxCommandEvent& event);
  112. void OnFireCustom(wxCommandEvent& event);
  113. void OnProcessCustom(wxCommandEvent& event);
  114. void OnUpdateUIPop(wxUpdateUIEvent& event);
  115. // regular event handlers used to highlight the events handling order
  116. void OnClickDynamicHandlerFrame(wxCommandEvent& event);
  117. void OnClickDynamicHandlerButton(wxCommandEvent& event);
  118. void OnClickStaticHandlerFrame(wxCommandEvent& event);
  119. private:
  120. // symbolic names for the status bar fields
  121. enum
  122. {
  123. Status_Main = 0,
  124. Status_Dynamic,
  125. Status_Push
  126. };
  127. void UpdateDynamicStatus(bool on)
  128. {
  129. #if wxUSE_STATUSBAR
  130. if ( on )
  131. {
  132. SetStatusText("You can now use \"Dynamic\" item in the menu");
  133. SetStatusText("Dynamic: on", Status_Dynamic);
  134. }
  135. else
  136. {
  137. SetStatusText("You can no more use \"Dynamic\" item in the menu");
  138. SetStatusText("Dynamic: off", Status_Dynamic);
  139. }
  140. #endif // wxUSE_STATUSBAR
  141. }
  142. // number of pushed event handlers
  143. unsigned m_nPush;
  144. // the button to whose event we connect dynamically
  145. wxButton *m_btnDynamic;
  146. // the button used to highlight the event handlers execution order
  147. MyEvtTestButton *m_testBtn;
  148. // any class wishing to process wxWidgets events must use this macro
  149. wxDECLARE_EVENT_TABLE();
  150. };
  151. // Define a custom event handler
  152. class MyEvtHandler : public wxEvtHandler
  153. {
  154. public:
  155. MyEvtHandler(size_t level) { m_level = level; }
  156. void OnTest(wxCommandEvent& event)
  157. {
  158. wxLogMessage(wxT("This is the pushed test event handler #%u"), m_level);
  159. // if we don't skip the event, the other event handlers won't get it:
  160. // try commenting out this line and see what changes
  161. event.Skip();
  162. }
  163. private:
  164. unsigned m_level;
  165. wxDECLARE_EVENT_TABLE();
  166. };
  167. // ----------------------------------------------------------------------------
  168. // constants
  169. // ----------------------------------------------------------------------------
  170. // IDs for the controls and the menu commands
  171. enum
  172. {
  173. // menu items
  174. Event_Quit = 1,
  175. Event_About,
  176. Event_Bind,
  177. Event_Connect,
  178. Event_Dynamic,
  179. Event_Push,
  180. Event_Pop,
  181. Event_Custom,
  182. Event_Test
  183. };
  184. // ----------------------------------------------------------------------------
  185. // event tables and other macros for wxWidgets
  186. // ----------------------------------------------------------------------------
  187. // The event tables connect the wxWidgets events with the functions (event
  188. // handlers) which process them.
  189. wxBEGIN_EVENT_TABLE(MyApp, wxApp)
  190. // Add a static handler for button Click event in the app
  191. EVT_BUTTON(MyEvtTestButton::BUTTON_ID, MyApp::OnClickStaticHandlerApp)
  192. wxEND_EVENT_TABLE()
  193. wxBEGIN_EVENT_TABLE(MyEvtTestButton, wxButton)
  194. // Add a static handler to this button itself for its own event
  195. EVT_BUTTON(BUTTON_ID, MyEvtTestButton::OnClickStaticHandler)
  196. wxEND_EVENT_TABLE()
  197. // This can be also done at run-time, but for the
  198. // simple menu events like this the static method is much simpler.
  199. wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
  200. EVT_MENU(Event_Quit, MyFrame::OnQuit)
  201. EVT_MENU(Event_About, MyFrame::OnAbout)
  202. #ifdef wxHAS_EVENT_BIND
  203. EVT_MENU(Event_Bind, MyFrame::OnBind)
  204. #endif // wxHAS_EVENT_BIND
  205. EVT_MENU(Event_Connect, MyFrame::OnConnect)
  206. EVT_MENU(Event_Custom, MyFrame::OnFireCustom)
  207. EVT_MENU(Event_Test, MyFrame::OnTest)
  208. EVT_MENU(Event_Push, MyFrame::OnPushEventHandler)
  209. EVT_MENU(Event_Pop, MyFrame::OnPopEventHandler)
  210. EVT_UPDATE_UI(Event_Pop, MyFrame::OnUpdateUIPop)
  211. EVT_MY_CUSTOM_COMMAND(wxID_ANY, MyFrame::OnProcessCustom)
  212. // the line below would also work if OnProcessCustom() were defined as
  213. // taking a wxEvent (as required by EVT_CUSTOM) and not wxCommandEvent
  214. //EVT_CUSTOM(wxEVT_MY_CUSTOM_COMMAND, wxID_ANY, MyFrame::OnProcessCustom)
  215. // Add a static handler in the parent frame for button event
  216. EVT_BUTTON(MyEvtTestButton::BUTTON_ID, MyFrame::OnClickStaticHandlerFrame)
  217. wxEND_EVENT_TABLE()
  218. wxBEGIN_EVENT_TABLE(MyEvtHandler, wxEvtHandler)
  219. EVT_MENU(Event_Test, MyEvtHandler::OnTest)
  220. wxEND_EVENT_TABLE()
  221. // Create a new application object: this macro will allow wxWidgets to create
  222. // the application object during program execution (it's better than using a
  223. // static object for many reasons) and also declares the accessor function
  224. // wxGetApp() which will return the reference of the right type (i.e. MyApp and
  225. // not wxApp)
  226. IMPLEMENT_APP(MyApp)
  227. // ============================================================================
  228. // implementation
  229. // ============================================================================
  230. // ----------------------------------------------------------------------------
  231. // the application class
  232. // ----------------------------------------------------------------------------
  233. // 'Main program' equivalent: the program execution "starts" here
  234. bool MyApp::OnInit()
  235. {
  236. if ( !wxApp::OnInit() )
  237. return false;
  238. // create the main application window
  239. MyFrame *frame = new MyFrame(wxT("Event wxWidgets Sample"),
  240. wxPoint(50, 50), wxSize(600, 340));
  241. // and show it (the frames, unlike simple controls, are not shown when
  242. // created initially)
  243. frame->Show(true);
  244. // Add a dynamic handler at the application level for the test button
  245. Connect(MyEvtTestButton::BUTTON_ID, wxEVT_BUTTON,
  246. wxCommandEventHandler(MyApp::OnClickDynamicHandlerApp));
  247. // success: wxApp::OnRun() will be called which will enter the main message
  248. // loop and the application will run. If we returned false here, the
  249. // application would exit immediately.
  250. return true;
  251. }
  252. // This is always the first to handle an event !
  253. int MyApp::FilterEvent(wxEvent& event)
  254. {
  255. if ( event.GetEventType() == wxEVT_BUTTON &&
  256. event.GetId() == MyEvtTestButton::BUTTON_ID )
  257. {
  258. wxLogMessage("Step 0 in \"How Events are Processed\":\n"
  259. "App::FilterEvent");
  260. }
  261. return wxApp::FilterEvent(event);
  262. }
  263. void MyApp::OnClickDynamicHandlerApp(wxCommandEvent& event)
  264. {
  265. wxLogMessage("Step 7, 3 in \"How Events are Processed\":\n"
  266. "App::DynamicHandler_InAppTable");
  267. event.Skip();
  268. }
  269. void MyApp::OnClickStaticHandlerApp(wxCommandEvent& event)
  270. {
  271. wxLogMessage("Step 7, 4 in \"How Events are Processed\":\n"
  272. "App::StaticHandler_InAppTable");
  273. wxLogMessage("Button click processed, there should be no more messages "
  274. "about handling events from the button.\n\n"
  275. "The log below shows the order in which the handlers "
  276. "were executed.");
  277. wxLog::FlushActive();
  278. event.Skip();
  279. }
  280. // ----------------------------------------------------------------------------
  281. // main frame
  282. // ----------------------------------------------------------------------------
  283. // frame constructor
  284. MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
  285. : wxFrame(NULL, wxID_ANY, title, pos, size)
  286. {
  287. SetIcon(wxICON(sample));
  288. // init members
  289. m_nPush = 0;
  290. m_btnDynamic = NULL;
  291. // create a menu bar
  292. wxMenu *menuFile = new wxMenu;
  293. menuFile->Append(Event_About, wxT("&About\tCtrl-A"), wxT("Show about dialog"));
  294. menuFile->AppendSeparator();
  295. menuFile->Append(Event_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program"));
  296. wxMenu *menuEvent = new wxMenu;
  297. #ifdef wxHAS_EVENT_BIND
  298. menuEvent->AppendCheckItem(Event_Bind, "&Bind\tCtrl-B",
  299. "Bind or unbind a dynamic event handler");
  300. #endif // wxHAS_EVENT_BIND
  301. menuEvent->AppendCheckItem(Event_Connect, wxT("&Connect\tCtrl-C"),
  302. wxT("Connect or disconnect the dynamic event handler"));
  303. menuEvent->Append(Event_Dynamic, wxT("&Dynamic event\tCtrl-D"),
  304. wxT("Dynamic event sample - only works after Connect"));
  305. menuEvent->AppendSeparator();
  306. menuEvent->Append(Event_Push, wxT("&Push event handler\tCtrl-P"),
  307. wxT("Push event handler for test event"));
  308. menuEvent->Append(Event_Pop, wxT("P&op event handler\tCtrl-O"),
  309. wxT("Pop event handler for test event"));
  310. menuEvent->Append(Event_Test, wxT("Test event\tCtrl-T"),
  311. wxT("Test event processed by pushed event handler"));
  312. menuEvent->AppendSeparator();
  313. menuEvent->Append(Event_Custom, wxT("Fire c&ustom event\tCtrl-U"),
  314. wxT("Generate a custom event"));
  315. // now append the freshly created menu to the menu bar...
  316. wxMenuBar *menuBar = new wxMenuBar();
  317. menuBar->Append(menuFile, wxT("&File"));
  318. menuBar->Append(menuEvent, wxT("&Event"));
  319. // ... and attach this menu bar to the frame
  320. SetMenuBar(menuBar);
  321. #if wxUSE_STATUSBAR
  322. CreateStatusBar(3);
  323. SetStatusText(wxT("Welcome to wxWidgets event sample"));
  324. SetStatusText(wxT("Dynamic: off"), Status_Dynamic);
  325. SetStatusText(wxT("Push count: 0"), Status_Push);
  326. #endif // wxUSE_STATUSBAR
  327. wxPanel * const panel = new wxPanel(this);
  328. wxSizer * const mainSizer = new wxBoxSizer(wxVERTICAL);
  329. wxSizer * const sizer = new wxBoxSizer(wxHORIZONTAL);
  330. const wxSizerFlags centreY(wxSizerFlags().Centre().Border());
  331. sizer->Add(new wxStaticText(panel, wxID_ANY,
  332. "This button will only work if its handler is dynamically connected"),
  333. centreY);
  334. m_btnDynamic = new wxButton(panel, Event_Dynamic, "&Dynamic button");
  335. sizer->Add(m_btnDynamic, centreY);
  336. mainSizer->Add(sizer, 1, wxEXPAND);
  337. mainSizer->Add(new wxStaticLine(panel), 0, wxEXPAND);
  338. mainSizer->Add(new wxStaticLine(panel), 0, wxEXPAND);
  339. m_testBtn = new MyEvtTestButton(panel, "Test Event Handlers Execution Order");
  340. // After being created, an instance of MyEvtTestButton already has its own
  341. // event handlers (see class definition);
  342. // Add a dynamic handler for this button event in the parent frame
  343. Connect(m_testBtn->GetId(), wxEVT_BUTTON,
  344. wxCommandEventHandler(MyFrame::OnClickDynamicHandlerFrame));
  345. // Bind a method of this frame (notice "this" argument!) to the button
  346. // itself
  347. m_testBtn->Connect(wxEVT_BUTTON,
  348. wxCommandEventHandler(MyFrame::OnClickDynamicHandlerButton),
  349. NULL,
  350. this);
  351. mainSizer->Add(m_testBtn);
  352. panel->SetSizer(mainSizer);
  353. }
  354. MyFrame::~MyFrame()
  355. {
  356. // we must pop any remaining event handlers to avoid memory leaks and
  357. // crashes!
  358. while ( m_nPush-- != 0 )
  359. {
  360. PopEventHandler(true /* delete handler */);
  361. }
  362. }
  363. // ----------------------------------------------------------------------------
  364. // standard event handlers
  365. // ----------------------------------------------------------------------------
  366. void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
  367. {
  368. // true is to force the frame to close
  369. Close(true);
  370. }
  371. void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
  372. {
  373. wxMessageBox("Event sample shows different ways of using events\n"
  374. "(c) 2001-2009 Vadim Zeitlin",
  375. "About wxWidgets Event Sample",
  376. wxOK | wxICON_INFORMATION, this);
  377. }
  378. void MyFrame::OnClickStaticHandlerFrame(wxCommandEvent& event)
  379. {
  380. wxLogMessage("Step 6, 4 in \"How Events are Processed\":\n"
  381. "parentWin::StaticHandler_InFrameTable");
  382. event.Skip();
  383. }
  384. // ----------------------------------------------------------------------------
  385. // dynamic event handling stuff
  386. // ----------------------------------------------------------------------------
  387. void MyFrame::OnClickDynamicHandlerFrame(wxCommandEvent& event)
  388. {
  389. wxLogMessage("Step 6, 3 in \"How Events are Processed\":\n"
  390. "parentWin::DynamicHandler_InFrameTable");
  391. event.Skip();
  392. }
  393. void MyFrame::OnClickDynamicHandlerButton(wxCommandEvent& event)
  394. {
  395. wxLogMessage("Step 3 in \"How Events are Processed\":\n"
  396. "parentWin::DynamicHandler_InButtonTable");
  397. event.Skip();
  398. }
  399. void MyFrame::OnDynamic(wxCommandEvent& event)
  400. {
  401. wxString origin;
  402. if ( event.GetEventObject() == this )
  403. origin = "menu item";
  404. else if ( event.GetEventObject() == m_btnDynamic )
  405. origin = "button";
  406. else
  407. origin = "unknown event source";
  408. wxMessageBox
  409. (
  410. "This message box is shown from the dynamically connected "
  411. "event handler in response to event generated by " + origin,
  412. "wxWidgets Event Sample", wxOK | wxICON_INFORMATION, this
  413. );
  414. }
  415. #ifdef wxHAS_EVENT_BIND
  416. void MyFrame::OnBind(wxCommandEvent& event)
  417. {
  418. if ( event.IsChecked() )
  419. {
  420. // as we bind directly to the button, there is no need to use an id
  421. // here: the button will only ever get its own events
  422. m_btnDynamic->Bind(wxEVT_BUTTON, &MyFrame::OnDynamic,
  423. this);
  424. // but we do need the id for the menu command as the frame gets all of
  425. // them
  426. Bind(wxEVT_MENU, &MyFrame::OnDynamic, this,
  427. Event_Dynamic);
  428. }
  429. else // disconnect
  430. {
  431. m_btnDynamic->Unbind(wxEVT_BUTTON,
  432. &MyFrame::OnDynamic, this);
  433. Unbind(wxEVT_MENU, &MyFrame::OnDynamic, this,
  434. Event_Dynamic);
  435. }
  436. UpdateDynamicStatus(event.IsChecked());
  437. }
  438. #endif // wxHAS_EVENT_BIND
  439. void MyFrame::OnConnect(wxCommandEvent& event)
  440. {
  441. if ( event.IsChecked() )
  442. {
  443. m_btnDynamic->Connect(wxID_ANY, wxEVT_BUTTON,
  444. wxCommandEventHandler(MyFrame::OnDynamic),
  445. NULL, this);
  446. Connect(Event_Dynamic, wxEVT_MENU,
  447. wxCommandEventHandler(MyFrame::OnDynamic));
  448. }
  449. else // disconnect
  450. {
  451. m_btnDynamic->Disconnect(wxID_ANY, wxEVT_BUTTON,
  452. wxCommandEventHandler(MyFrame::OnDynamic),
  453. NULL, this);
  454. Disconnect(Event_Dynamic, wxEVT_MENU,
  455. wxCommandEventHandler(MyFrame::OnDynamic));
  456. }
  457. UpdateDynamicStatus(event.IsChecked());
  458. }
  459. // ----------------------------------------------------------------------------
  460. // push/pop event handlers support
  461. // ----------------------------------------------------------------------------
  462. void MyFrame::OnPushEventHandler(wxCommandEvent& WXUNUSED(event))
  463. {
  464. PushEventHandler(new MyEvtHandler(++m_nPush));
  465. #if wxUSE_STATUSBAR
  466. SetStatusText(wxString::Format(wxT("Push count: %u"), m_nPush), Status_Push);
  467. #endif // wxUSE_STATUSBAR
  468. }
  469. void MyFrame::OnPopEventHandler(wxCommandEvent& WXUNUSED(event))
  470. {
  471. wxCHECK_RET( m_nPush, wxT("this command should be disabled!") );
  472. PopEventHandler(true /* delete handler */);
  473. m_nPush--;
  474. #if wxUSE_STATUSBAR
  475. SetStatusText(wxString::Format(wxT("Push count: %u"), m_nPush), Status_Push);
  476. #endif // wxUSE_STATUSBAR
  477. }
  478. void MyFrame::OnTest(wxCommandEvent& WXUNUSED(event))
  479. {
  480. wxLogMessage(wxT("This is the test event handler in the main frame"));
  481. }
  482. void MyFrame::OnUpdateUIPop(wxUpdateUIEvent& event)
  483. {
  484. event.Enable( m_nPush > 0 );
  485. }
  486. // ----------------------------------------------------------------------------
  487. // custom event methods
  488. // ----------------------------------------------------------------------------
  489. void MyFrame::OnFireCustom(wxCommandEvent& WXUNUSED(event))
  490. {
  491. wxCommandEvent eventCustom(wxEVT_MY_CUSTOM_COMMAND);
  492. wxPostEvent(this, eventCustom);
  493. }
  494. void MyFrame::OnProcessCustom(wxCommandEvent& WXUNUSED(event))
  495. {
  496. wxLogMessage(wxT("Got a custom event!"));
  497. }