Skip to content

Instantly share code, notes, and snippets.

@anko
Created March 13, 2019 03:10
Show Gist options
  • Save anko/34bc5bac02661927e42e1880a32d89e0 to your computer and use it in GitHub Desktop.
Save anko/34bc5bac02661927e42e1880a32d89e0 to your computer and use it in GitHub Desktop.
An example of sending a synthetic GdkEvent

What this

I picked this up from this email thread from 2004 and edited it enough to compile on recent GDK/GTK. Thanks to Tommi Komulainen and Juhana Sadeharju!

Context for why I'm reading these things: anko/hudkit#3

Run it

$ make
[ ... warnings and deprecation notices, but it compiles ... ]
$ ./program
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
static gboolean
on_timeout (gpointer user_data)
{
GtkWidget *widget = user_data;
GdkKeymapKey *keys;
gint n_keys;
if (gdk_keymap_get_entries_for_keyval (gdk_keymap_get_default (),
'o', &keys, &n_keys))
{
guint16 hardware_keycode;
GdkEventKey *event;
/* we can pick any hardware_keycode that generates GDK_o */
hardware_keycode = keys[0].keycode;
g_free (keys);
/* synthesize Alt+O key press */
event = (GdkEventKey*)gdk_event_new (GDK_KEY_PRESS);
event->window = gtk_widget_get_window(widget);
event->state = GDK_MOD1_MASK; /* Alt */
event->hardware_keycode = hardware_keycode; /* +O */
/* these are optional but possibly nice to have */
event->keyval = gdk_unicode_to_keyval ('o');
event->length = 1;
event->string = g_strdup ("o");
/* the rest are no-ops */
event->send_event = FALSE; /* seems unused except for dnd */
event->time = GDK_CURRENT_TIME;
gtk_main_do_event (event);
gdk_event_free (event);
}
return FALSE;
}
static gboolean
on_key_press_event (GtkWidget *widget, GdkEventKey *event)
{
g_print ("send_event=%d, state=%u, keyval=%u, length=%d, string='%s', hardware_keycode=%u, group=%u\n",
event->send_event, event->state, event->keyval, event->length, event->string, event->hardware_keycode,
event->group);
return FALSE;
}
int
main (int argc, char **argv)
{
GtkWidget *win;
gtk_init (&argc, &argv);
win = gtk_message_dialog_new (NULL, 0, GTK_MESSAGE_QUESTION,
GTK_BUTTONS_OK_CANCEL, "OK?");
g_signal_connect (win, "key-press-event", G_CALLBACK(on_key_press_event), 0);
g_timeout_add (2500, on_timeout, win);
gtk_dialog_run (GTK_DIALOG(win));
return 0;
}
program: main.c
clang -o "$@" $$(pkg-config --cflags --libs gtk+-3.0 gdk-3.0) "$<"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment