How can I monitor keypresses in GTK?

90 views Asked by At

I'm looking to get capture keypresses in my program, but am hitting a wall.

  1. I'm working from this answer: How do I Check for the Key Pressed in GTK3 (C)? (last answer)
  2. I swapped in GtkEventControllerKey for GtkEventKey which I understand is the proper way now.

Here's my code:

void on_window_main_key_press_event(GtkWidget *widget, GtkEventControllerKey *key, gpointer user_data) {
    guint TheKeyThatWasPressed = key->keyval;
}

Which yields the error:

error: invalid use of incomplete typedef ‘GtkEventControllerKey’ {aka ‘struct _GtkEventControllerKey’}
  147 |     guint TheKeyThatWasPressed = key->keyval;
1

There are 1 answers

0
Holger On

I hope I have understood you correctly. Want to keep track of which keys have been pressed? Here's an example of how I would solve this problem.

include <gtk/gtk.h>

static gboolean on_key_pressed(GtkEventControllerKey *controller,` 
                           guint keyval,
                            guint keycode,
                            GdkModifierType state,
                            gpointer user_data)
{
    gunichar unicode = gdk_keyval_to_unicode(keyval);
    gchar *letter = g_ucs4_to_utf8(&unicode, 1, NULL, NULL, NULL);

    g_print("keyval: %u\n", keyval);
    g_print("keycode: %u\n",keycode);
    g_print("letter pressed: %s\n", letter);

    g_free(letter);

    return GDK_EVENT_PROPAGATE;
}


static void
activate (GtkApplication *app,
          gpointer        user_data)
{
  GtkWidget *window;

  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);

  GtkEventController*  keyevent = gtk_event_controller_key_new ();
  gtk_widget_add_controller(window,keyevent);

  g_signal_connect(keyevent,"key-pressed",G_CALLBACK(on_key_pressed),NULL);

  gtk_window_present (GTK_WINDOW(window));
}

int
main (int    argc, char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example",   G_APPLICATION_DEFAULT_FLAGS);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status; 
}