Wxwidgets 下键盘事件响应

参照http://wiki.wxwidgets.org/Catching_key_events_globally

试了两个方法

第一个可以让不同的panel有不同的键盘响应

第二个作为全局的键盘响应 代码要放边很多

具体为

第一个

先添加custom event handler

class CEventPropagator : public wxEvtHandler
{
public:
    CEventPropagator();
    static void registerFor(wxWindow* win);

private:
    void onKeyDown(wxKeyEvent& aEvent);
    void onKeyUp(wxKeyEvent& aEvent);
};


// ------------------------------------------------------------------------------------

CEventPropagator::CEventPropagator()
{
    // Event connections
    this->Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(CEventPropagator::onKeyDown));
    this->Connect(wxEVT_KEY_UP,   wxKeyEventHandler(CEventPropagator::onKeyUp));
}

void CEventPropagator::onKeyDown(wxKeyEvent& aEvent)
{
    printf("CEventPropagator::onKeyDown\n");
    aEvent.ResumePropagation(1);
    aEvent.Skip();
}

void CEventPropagator::onKeyUp(wxKeyEvent& aEvent)
{
    printf("CEventPropagator::onKeyUp\n");
    aEvent.ResumePropagation(1);
    aEvent.Skip();
}

void CEventPropagator::registerFor(wxWindow* win)
{
    wxWindowListNode* childNode = win->GetChildren().GetFirst();
    while (childNode)
    {
        childNode->GetData()->PushEventHandler(new CEventPropagator());
        childNode = childNode->GetNext();
    }
}

MyFrame添加声明

void OnKeyDown(wxKeyEvent& event);

事件表中

EVT_KEY_DOWN(MyFrame::OnKeyDown)

具体实现

void MyFrame::OnKeyDown(wxKeyEvent& event) {
	//Key C for Print Image
	std::cout << "Pressed key {" << event.GetKeyCode() << "}\n";
	if(event.GetKeyCode() ==67) cout<<"gfd"<<"\n";
	event.Skip();
}

将响应注册到窗口中

    CEventPropagator::registerFor(glPane);
    glPane->Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MyFrame::OnKeyDown), NULL, this);
    drawPane->Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MyFrame::OnKeyDown), NULL, this);


第二个

MyApp声明出添加

	int FilterEvent(wxEvent& event);

以及实现

int MyApp::FilterEvent(wxEvent& event)
{
    if (event.GetEventType() == wxEVT_KEY_DOWN)
    {
    	std::cout << "http://blog.csdn.net/boksic" << ((wxKeyEvent&)event).GetKeyCode() << "}\n";
        return true;
    }

    return -1;
}









你可能感兴趣的:(Wxwidgets 下键盘事件响应)