tux tux
tux tux

Reputation: 25

How to generate keypress event programmatically

I am trying to develop a GTK application in Linux. In this scenario I do not have a keyboard attached, and I need to generate key_press_event for GTK.

I have written a multithreaded program to generate key press, but it works only once; after that the keypress is not getting generated.

GtkWidget *window; is declared as global in order to get the same window handler for both threads.

The program has 2 threads. The first holds the GTK main and gtk screen display code. The second generates key events according to user requirements.

I ported the if() block into my code, but the result is the same.

The signal is generated once. After that it's not coming to 2nd thread (signal generation thread).

I have put some debug prints, but they are not executed. It seems to be waiting on gtk_main in the first thread.

My code is the following:

void S1(void)
{
    GtkWidget *Win_1;
    GtkBuilder *builder;        
    builder = gtk_builder_new ();
    gtk_builder_add_from_file (builder, "/home/glade/glade1.glade", NULL);
    window = GTK_WIDGET (gtk_builder_get_object (builder, "Win_1"));        
    g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), G_OBJECT(window));
    g_signal_connect (G_OBJECT (window), "key_press_event", G_CALLBACK (kp_event), NULL);
    gtk_widget_show_all(window);
    gtk_main(); 
}

kp_event()
{
    gtk_widget_destroy (window);            
    S2();
}

S2 is the same as S1, only differing in their screen item. I am calling S2 from keypress handler of S1 and vice versa.

Since I have no keyboards attached, I need to change two screens based on some user input via sockets or something.

Upvotes: 2

Views: 2940

Answers (1)

jcoppens
jcoppens

Reputation: 5440

Have a look at this article, particularly the following snippet of code:


/* synthesize Alt+O key press */
event = gdk_event_new (GDK_KEY_PRESS);
event->key.window = widget->window;

This line should actually read:

event->key.window = g_object_ref (widget->window);

Otherwise you'll get interesting error messages later on if you destroy widgets. Took some time to figure out for myself. :)


Upvotes: 2

Related Questions