![](/img/trans.png)
[英]Event handler function to wxButton with Bind() - wxWidgets 3.0
[英]Creating a handler function with Bind to handle clicked menu item - wxWidgets 3.0
我想知道如何使用Bind函數在wxWidgets 3.0,C ++中創建一個簡單的事件處理程序。
為了開始我的實驗,我創建了一個非常簡單的應用程序 - 一個帶有菜單的主框架和菜單中的幾個項目。 到目前為止沒有任何問題,所有都出現了預期 我使用的代碼的一部分是:
//create a menu bar
wxMenuBar* mbar = new wxMenuBar();
wxMenu* fileMenu = new wxMenu(_T(""));
fileMenu->Append(item1, _("&Item_1"), _("Select item 1"));
mbar->Append(fileMenu, _("&File"));
現在我想使用Bind創建一個簡單的處理程序,如果從菜單中選擇Item_1,它會彈出一個消息框,例如:
wxMessageBox( "You have selected Item 1", "Your selection", wxOK | wxICON_INFORMATION );
請注意,彈出消息框只是一個簡單的例子,我選擇快速掌握概念並查看結果。 如果可能的話,我希望Bind事件處理程序盡可能通用,用於任意事件和操作。
#include <wx/wx.h>
#define item1 (wxID_HIGHEST + 1)
class CApp : public wxApp
{
public:
bool OnInit() {
// Create the main frame.
wxFrame * frame = new wxFrame(NULL, wxID_ANY, "demo");
// Create a menu bar.
wxMenuBar* mbar = new wxMenuBar();
wxMenu* fileMenu = new wxMenu(_T(""));
fileMenu->Append(item1, _("&Item_1"), _("Select item 1"));
mbar->Append(fileMenu, _("&File"));
frame->SetMenuBar(mbar);
// Bind an event handling method.
#if __cplusplus < 201103L
frame->Bind(wxEVT_MENU, &CApp::item1_OnMenu, this, item1);
#else
frame->Bind(wxEVT_MENU, [](wxCommandEvent & evt)->void{
wxMessageBox("You have selected Item 1", "Your selection", wxOK | wxICON_INFORMATION);
}, item1);
#endif
// Enter the message loop.
frame->Show(true);
return this->wxApp::OnInit();
}
#if __cplusplus < 201103L
protected:
void item1_OnMenu(wxCommandEvent & evt) {
wxMessageBox("You have selected Item 1", "Your selection", wxOK | wxICON_INFORMATION);
}
#endif
};
DECLARE_APP(CApp)
IMPLEMENT_APP(CApp)
方法wxEvtHandler::Bind
有3個重載。 以上只展示了其中的2個。
對於可用的事件類型,這將是Bind
的第一個參數,請參閱wx / event.h。 event.h還告訴我們應該使用哪個事件類。 例如,
#define EVT_MENU(winid, func) wx__DECLARE_EVT1(wxEVT_MENU, winid, wxCommandEventHandler(func))
注意wxCommandEventHandler
,刪除后綴Handler
,剩下的將是事件類wxCommandEvent
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.