“key-release-event” not triggered

2019-08-20 10:35发布

问题:

Consider the following code:

#include <gtk/gtk.h>

static void stop(GtkWidget *window, GdkEventKey *key, gboolean *key_held)
{
        *key_held = FALSE;
        g_print("stopped!\n");
}

static void counter(GtkWidget *window, GdkEventKey *key, gpointer user_data)
{
        gboolean key_held = TRUE;
        gulong signal_ID = g_signal_connect(window, "key-release-event", G_CALLBACK(stop), &key_held);

        for (unsigned long int i = 0;key_held;i++)
        {   
                g_print("%li\n", i); 
        }   

        g_signal_handler_disconnect(window, signal_ID);
}

int main(int argc, char **argv)
{
        gtk_init(&argc, &argv);

        GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        gtk_widget_add_events(window, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);

        g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL);
        g_signal_connect(window, "key-press-event", G_CALLBACK(counter), NULL);

        gtk_widget_show(window);

        gtk_main();
}

It's simple: the counter starts to count from 0 when the user presses a key and continues to count until the user release the key...

Or that's at least how it's supposed to work. What actually happens is that when a user presses a key, the counter starts and doesn't stop when the user release the key. The only way to stop counting is to terminate the program. Also, not only the "key-release-event" is not triggered but "delete-event" isn't too: I have to press Ctrl+C to terminate the program.

标签: c gtk gtk3