How to emit a keypress event in gtk-rs


I’m trying to learn Rust, and writing a GTK app as an exercise. I want to emit synthesized keypress events. I can create the event struct with
let mut ev: gdk::Event = gdk::Event::new(gdk::EventType::KeyPress);
and send it with
gtk::main_do_event(&mut ev);
but of course it’s of no use without suitable values in the Event fields. However, I can’t find functions or any other way to set those values.

Grateful for any help on this; not sure what I’m doing wrong.



I’m not familiar with the gdk crate’s api, but this crate might be interesting for you:
(seems to support linux only at the moment)

I’m not sure whether you’ll be able to “click” anything outside your own app by creating gdk::Events.



Thanks for the amazingly rapid response! :slight_smile:
I’ll take a look at rsbot, sounds like something that may come in handy anyway, and the code may contain some clues on generating events.

I don’t want to click anything other than my own app, but I do want to send ‘fake’ events (flagged as such) for the app to process in its normal key press handler.



Had a look at rsbot, it uses Xtest, which uses xlib, so no clues as to how to do it with gtk-rs. :frowning_face:



OK, after LOTS of experimenting, I have now managed to set all the required fields in the gdk::EventKey struct and send a synthesized key-press event.


  1. gdk::Event::new(gdk::EventType::KeyPress) returns an immutable reference, so have to convert that to mutable by pointer manipulation.
  2. gdk::EventKey has a few setter functions, but they don’t cover most of the fields that must be set.
  3. Need to set a device, otherwise GTK outputs numerous warning messages; at least gdk::EventKey has a set_device(&dev) function.
  4. For the window field, needs a mutable pointer to the gdk_sys::GdkWindow; more pointer manipulation.
  5. Last but definitely not least, need to increment the ref count for the GTK object of the window, requiring more pointer manipulation on gdk_sys::GdkWindow.

If anyone is interested, I can post the code.

I’m sure there must be proper Rustic ways of doing all this (if not, there should be!) but I have not found anything to date, not helped by my newbie status as a Rust coder. Grateful for any help in that direction.



You could try asking for a comment on your code here