Search code examples
c++wxwidgetskeyevent

Binding wxEVT_CHAR_HOOK not working in wxWidgets 3.1.2


I'm trying to have a function be called every time a key is pressed. For some reason I can't bind the wxEVT_CHAR_HOOK event to a function. There is no probelm with creating a button and binding the button to a function when it is pressed. I'm using Visual Studio 2017 and wxWidgets 3.1.2

I have already tried to exchange wxEVT_CHAR_HOOK with wxEVT_KEY_DOWN and this doesn't work. However, binding the same function with another event (like wxEVT_BUTTON) DOES work.

enum
{
    ID_Hello = wxID_HIGHEST + 1,
    ID_Button1 = wxID_HIGHEST + 2,
    ID_Panel1 = wxID_HIGHEST + 3

};
wxIMPLEMENT_APP(MyApp);
bool MyApp::OnInit()
{
    MyFrame *frame = new MyFrame();
    frame->Show(true);
    return true;
}
MyFrame::MyFrame() : wxFrame(NULL, wxID_ANY, "Hello World")
{
    panel1 = new wxPanel(this, ID_Panel1, wxDefaultPosition, wxDefaultSize);

    wxSize buttonSizeHelloWorld = wxSize(200, 200);
    wxPoint buttonPosHelloWorld = wxPoint(50, 50);

    HelloWorldButton = new wxButton(panel1, ID_Button1,
        "Hello", buttonPosHelloWorld, buttonSizeHelloWorld);

        //These work fine
        Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
    Bind(wxEVT_BUTTON, &MyFrame::OnExit, this, ID_Button1);

        //This is what fails
    Bind(wxEVT_CHAR_HOOK, &MyFrame::ProcessKeypress, this);

}

void MyFrame::ProcessKeypress(wxCommandEvent& event) {
    wxLogMessage("A key was pressed");
}
void MyFrame::OnHello(wxCommandEvent& event)
{
    wxLogMessage("Hello world from wxWidgets!");
}
void MyFrame::OnExit(wxCommandEvent& event)
{
    Close(true);
}

The error message (which I searched for but did not find something useful):

C2664 "void wxEventFunctorMethod::CheckHandlerArgument(EventArg *)" : Convertation of argument 1 of "wxKeyEvent *" to "EventArg *" not possible (event.h -> line: 374)


Solution

  • A handler for wxEVT_CHAR_HOOK must take wxKeyEvent& argument and not wxCommandEvent& and the error message is telling you that exactly this (you should also see that EventArg is wxCommandEvent in the compiler output).