Search code examples
c++keypressgtkmm

gtkmm: How to detect arrow key is pressed


What event can i connect to in order to detect arrow keys being pressed when a user is in a window.

So far i have tried to connect via on_key_press_event and i checked keyval, hardware_keycode, and state.

#include <gtkmm.h>
#include <iostream>

class MyWindow : public Gtk::Window
{
public:
    MyWindow();
    bool onKeyPress(GdkEventKey*);
};

MyWindow::MyWindow()
{
    set_title("arrow_button_test");
    this->signal_key_press_event().connect( sigc::mem_fun( *this, &MyWindow::onKeyPress ) );
}

bool MyWindow::onKeyPress(GdkEventKey* event)
{
    std::cout << event->keyval << ' ' << event->hardware_keycode << ' ' << event->state << std::endl;

    return false;
}

int main(int argc, char** argv)
{
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "com.almost-university.gtkmm.arrow_button_press");

    MyWindow window;    

    app->run(window);

    return 0;
}

This code generates no output on arrow keys, meaning that event isn't even fired off.


Solution

  • If you change

    this->signal_key_press_event().connect(
        sigc::mem_fun(*this, &MyWindow::onKeyPress));
    

    to

    this->signal_key_press_event().connect(
        sigc::mem_fun(*this, &MyWindow::onKeyPress), false);
    

    your signal handler should receive the events. That false argument is for the after flag. It is true by default, meaning that other signal handlers may intercept the signal before MyWindow::onKeyPress, since it is the last one.