Hey all! I was looking for a way to use GDK without using GTK+. There are basically two ways. Blocking and non-blocking. Here is the code I managed to get (very basic working examples). This is just a way of getting rid of GTK+, where it is not needed.
Blocking (if nothing happens, it just waits for events):
Code:
#include <glib.h>
#include <gdk/gdk.h>
GMainLoop *mainloop;
static void event_func(GdkEvent *ev, gpointer data) {
switch(ev->type) {
case GDK_KEY_PRESS:
g_printf("key press [%s]\n", ev->key.string);
break;
case GDK_DELETE:
g_main_loop_quit(mainloop);
break;
}
}
int main(int argc, char **argv) {
gdk_init(&argc, &argv);
GdkWindowAttr attr;
attr.title = argv[0];
attr.event_mask = GDK_KEY_PRESS_MASK | GDK_STRUCTURE_MASK | GDK_EXPOSURE_MASK;
attr.window_type = GDK_WINDOW_TOPLEVEL;
attr.wclass = GDK_INPUT_OUTPUT;
attr.width = 400;
attr.height = 300;
GdkWindow *win = gdk_window_new(NULL, &attr, 0);
gdk_window_show(win);
gdk_event_handler_set(event_func, NULL, NULL); // this is used by GTK+ internally. We just use it for ourselves here
mainloop = g_main_loop_new(g_main_context_default(), FALSE); // we use the default main context because that's what GDK uses internally
g_main_loop_run(mainloop);
gdk_window_destroy(win);
return 0;
}
Non-blocking (it processes events then runs some idle code. useful for e.g OpenGL programs that want maximum FPS):
Code:
#include <gdk/gdk.h>
int main(int argc, char **argv) {
gdk_init(&argc, &argv);
GdkWindowAttr attr;
attr.title = argv[0];
attr.event_mask = GDK_KEY_PRESS_MASK | GDK_STRUCTURE_MASK | GDK_EXPOSURE_MASK;
attr.window_type = GDK_WINDOW_TOPLEVEL;
attr.wclass = GDK_INPUT_OUTPUT;
attr.width = 400;
attr.height = 300;
GdkWindow *win = gdk_window_new(NULL, &attr, 0);
gdk_window_show(win);
gboolean done = FALSE;
while(!done) {
while(gdk_events_pending()) {
GdkEvent *ev = gdk_event_get();
if(ev) {
switch(ev->type) {
case GDK_DELETE:
done = TRUE;
break;
}
gdk_event_free(ev);
}
}
// now do idle stuff
}
gdk_window_destroy(win);
return 0;
}