How to get the keys a user presses inside a GtkApplication?

I am trying to get the keys that a user is typing in without having an editable Entry or TextView. I saw an example with window.connect on an older version. I tried getting the “key_press” via the connect_closure, but keep getting an error that ‘key_press’ is not found on GtkApplicationWindow.

What is the best way to achieve this goal? What am I doing wrong?

Help will be highly appreciated.

Thanks, Alex

use gdk::prelude::{ApplicationExt, ApplicationExtManual, ObjectExt};
use glib::ToValue;
use gtk::glib;
use gtk::traits::{GtkWindowExt, WidgetExt};

static APP_ID: &str = "org.gtkrs.keylistener";

fn build_ui(application: &gtk::Application) {
    let window = gtk::ApplicationWindow::builder()
        .application(application)
        .title("Key Listener Experiment")
        .build();

    let gclosure = glib::RustClosure::new(|values| {
        println!("values: {:#?}", values);
        // Values is an Event object?
        let event_type = &values[1].get::<gdk::EventType>().unwrap();
        let raw_event = &values[1].get::<gdk::Event>().unwrap();
        println!("event_type: {:#?}", event_type);
        println!("raw_event: {:#?}", raw_event);
        println!("raw_event_keycode(): {:#?}", raw_event.keycode());
        println!("raw_event_keyval(): {:#?}", raw_event.keyval());
        Some("Hello".to_value())
    });
    window.connect_closure("key_press", false, gclosure);

    let vbox = gtk::Box::builder()
        .spacing(5)
        .orientation(gtk::Orientation::Vertical)
        .build();

    window.set_child(Some(&vbox));

    window.show();
}

fn main() {
    let app = gtk::Application::builder().application_id(APP_ID).build();
    app.connect_activate(build_ui);
    app.run();
}

You can use EventControllerKey by listening for keys with connect_key_pressed and then adding to the window using window.add_controller.

1 Like
  // Create an EventController
    let eventctl = gtk::EventControllerKey::new();
    eventctl.connect_key_pressed( ); // What are the arguments of the function ... ?
    // connect_key_pressed
    window.add_controller(eventctl);

I can’t understand what arguments to pass to eventcontroller.connect_key_pressed? I see that it expects a Key, u32, and a gdk::ModifierType. But I can’t seem to get past this. And I can’t find any examples anywhere.:frowning: Help would be appreciated.

impl EventControllerKey {
    pub fn connect_key_pressed<
        F: Fn(&EventControllerKey, Key, u32, gdk::ModifierType) -> glib::signal::Inhibit + 'static,
    >(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn key_pressed_trampoline<
            F: Fn(&EventControllerKey, Key, u32, gdk::ModifierType) -> glib::signal::Inhibit + 'static,
        >(
            this: *mut ffi::GtkEventControllerKey,
            keyval: libc::c_uint,
            keycode: libc::c_uint,
            state: gdk::ffi::GdkModifierType,
            f: glib::ffi::gpointer,
        ) -> glib::ffi::gboolean {
            let f: &F = &*(f as *const F);
            f(
                &from_glib_borrow(this),
                from_glib(keyval),
                keycode,
                from_glib(state),
            )
            .into_glib()
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"key-pressed\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    key_pressed_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

The docs do provide the names and descriptions of the arguments, although they are a translation from the C docs so it is not the most understandable: EventControllerKey in gtk4 - Rust

Sorry about that, not sure how we could improve that for gtk-rs, because Rust does not support named arguments in a Fn bound. But if you write your handler you could put the names in:

eventctl.connect_key_pressed(|eventctl, keyval, keycode, state| {
    // ....
});

You can see there keyval and keycode correspond to the usage in your sample code, and the last argument is the modifiers (shift/ctrl/alt/etc) held when the key was pressed. The names are also in those generated trampoline functions if you prefer to look at the implementation to grab them.

1 Like