Programming Tips - gtkmm4.x: get a key press in the main window

Date: 2025jun24 Language: C++ Platform: gtkmm4 Keywords: GTK, GNOME, gtkmm-4.0 Q. gtkmm4.x: get a key press in the main window A.
#include <gtkmm.h> #include <gtkmm/window.h> #include <gtkmm/eventcontrollerkey.h> class MyWindow : public Gtk::Window { public: bool onKeyPressed(const guint keyval, const guint keycode, const Gdk::ModifierType state) { // Check for whatever key you want. // Here we're look for a 'q' and quiting. if (keyval == GDK_KEY_q) { get_application()->quit(); } return false; } MyWindow() { auto callback = sigc::mem_fun(*this, &MyWindow::onKeyPressed); auto controller = Gtk::EventControllerKey::create(); controller->signal_key_pressed().connect(callback, false); add_controller(controller); } }; int main(int argc, char *argv[]) { auto app = Gtk::Application::create(); return app->make_window_and_run<MyWindow>(argc, argv); }