Hello, this is my first post here.
I'm playing around with Gtk+ and Xlib. I'm trying to get the X window ID of the active window, and then display that ID in a Gtk label. However, when I run it, it seg faults. I've narrowed it down to XGetInputFocus
, but I'm stuck, because it seems like I'm supplying it with the parameter types it needs. All three parameters are *Display
, *Window
and *int
, which is what I'm supplying it, according to https://tronche.com/gui/x/xlib/input/XGetInputFocus.html
-
What am I doing wrong?
- Also, when I compile with
gcc -Wall
pkg-config --cflags gtk+-3.0-o inputfocus inputfocus.c
pkg-config --libs gtk+-3.0-lX11
I get a warning because sprintf expects an unsigned int because I provide %u as a format specifier. However, the source "focus" is of type Window. I referenced the definition of Window, and it is typedefed as XID, and XID is typedefed as unsigned long int.
How should I properly convert or cast that to a type sprintf is satisfied with?
#include <gtk/gtk.h>
#include <gtk/gtkx.h>
#include <X11/Xlib.h>
#include <stdlib.h>
static void activate (GtkApplication* app, gpointer user_data) {
GtkWidget *window;
GtkWidget *glblLabel = gtk_label_new("Hello!");
GdkWindow *gdkwin;
GdkDisplay *gdkdisplay;
Display *dpy;
Window xwindow;
Window *focus;
char *text = malloc(sizeof(Window) +1);
int *revert_to = 0;
// Set up the application, window, and widgets
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "Window");
gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
gtk_container_add(GTK_CONTAINER(window), glblLabel);
gtk_widget_show_all (window);
gdkwin = gtk_widget_get_window(window); // Get GtkWidget *window's GdkWindow
gdkdisplay = gdk_window_get_display(gdkwin); // Then use it to get its GdkDisplay
dpy = GDK_DISPLAY_XDISPLAY(gdkdisplay); // Use that to get its X11 display
xwindow = GDK_WINDOW_XID(gdkwin); // Get GtkWidget *window's X window ID
focus = &xwindow;
// XGetInputFocus returns the active X window in focus
XGetInputFocus(dpy, focus, revert_to);
sprintf(text, "%u", focus); // Convert active window's ID to string
gtk_label_set_text(GTK_LABEL(glblLabel), text); // Then display it in glblLabel
}
int main (int argc, char **argv) {
GtkApplication *app;
int status;
app = gtk_application_new ("org.techstuffonly.inputtest", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}