The following consists of just a button that when clicked can produce output on the console. (The output is just the value of a local loop counter and a global variable.)
EDIT: The point is the code is to investigate how gtk_main_interation() works; so I do not want to wrap that call around a gtk_events_pending() loop. The code is purely pedagogical in nature.
The strange part of the code is that instead the "clicked" event handler there's a loop that calls gtk_main_iteration(). gtk_main_iteration is supposed to block if there are no events pending. Yet playing around with this little app shows that the GTK main loop is catching some event every second or so even if nothing is happening. To see this, try just clicking and releasing the button and then letting go of the mouse (without moving the cursor at all).
Presumably this event is being generated by the X server (or the GTK main loop) as some sort of timing thing. I don't know what this event is called and google searches are failing me.
#include <gtk/gtk.h>
#include <glib.h>
#include <gmp.h>
#include <unistd.h>
#define UNUSED(x) (void)(x)
typedef struct _Data {
GtkWidget *window1,
*button1;
} Data;
int g=0;
void on_button1_clicked(GtkWidget *widget, Data *data) {
int l=0;
UNUSED(widget);
UNUSED(data);
for(l=0;l<10;++l) {
gtk_main_iteration();
printf("l=%d g=%d|",l,g++);
fflush(stdout);
}
printf("\n\n");
}
int main (int argc, char *argv[]) {
Data *data;
gtk_init(&argc, &argv);
data=g_slice_new0(Data);
/* add widgets and objects to our structure */
data->window1=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(data->window1),250,250);
data->button1=gtk_button_new_with_label("Start");
gtk_container_add(GTK_CONTAINER(data->window1),GTK_WIDGET(data->button1));
gtk_signal_connect(GTK_OBJECT(data->window1), "delete-event",
gtk_main_quit, NULL);
gtk_signal_connect(GTK_OBJECT(data->button1), "clicked",
G_CALLBACK(on_button1_clicked), NULL);
gtk_widget_show_all(GTK_WIDGET(data->window1));
gtk_main();
/* Don't forget to free the memory! */
g_slice_free(Data, data);
return 0;
}
I'm compiling with
gcc -Wall -Wextra -Wconversion -pedantic `pkg-config --cflags --libs gtk+-2.0` events.c -o events