Skip to content

Instantly share code, notes, and snippets.

@mafrasi2
Created October 28, 2016 01:51
Show Gist options
  • Save mafrasi2/4ee01e0ba4dad20cf7a80ae463f32fca to your computer and use it in GitHub Desktop.
Save mafrasi2/4ee01e0ba4dad20cf7a80ae463f32fca to your computer and use it in GitHub Desktop.
/*
* Compile with -lxcb -lxcb-randr
*/
#include <stdio.h>
#include <stdlib.h>
#include <xcb/xcb.h>
#include <xcb/randr.h>
int main() {
xcb_connection_t* conn;
xcb_screen_t* screen;
xcb_window_t window;
xcb_generic_event_t* evt;
xcb_randr_screen_change_notify_event_t* randr_evt;
xcb_timestamp_t last_time;
int monitor_connected = 1;
conn = xcb_connect(NULL, NULL);
screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
window = screen->root;
xcb_randr_select_input(conn, window, XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE);
xcb_flush(conn);
while ((evt = xcb_wait_for_event(conn)) != NULL) {
if (evt->response_type & XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE) {
randr_evt = (xcb_randr_screen_change_notify_event_t*) evt;
if (last_time != randr_evt->timestamp) {
last_time = randr_evt->timestamp;
monitor_connected = !monitor_connected;
if (monitor_connected) {
printf("Monitor connected\n");
} else {
printf("Monitor disconnected\n");
}
}
}
free(evt);
}
xcb_disconnect(conn);
}
@BartonCline
Copy link

BartonCline commented Dec 8, 2016

Monitor screen changed events in Linux.
Thanks for porting my python implementation found here.

@bpmartin20
Copy link

I realize this is pretty old. I'd love to be able to use it, but as of Ubuntu 22.04 I haven't been able to compile it. I've installed every libxcb* package available, and I think I've built my Makefile correctly, but I keep getting undefined references:

/usr/bin/ld: monitor_watcher.c:(.text+0x1e): undefined reference to `xcb_connect'
/usr/bin/ld: monitor_watcher.c:(.text+0x2e): undefined reference to `xcb_get_setup'
/usr/bin/ld: monitor_watcher.c:(.text+0x36): undefined reference to `xcb_setup_roots_iterator'
/usr/bin/ld: monitor_watcher.c:(.text+0x59): undefined reference to `xcb_randr_select_input'
/usr/bin/ld: monitor_watcher.c:(.text+0x65): undefined reference to `xcb_flush'
/usr/bin/ld: monitor_watcher.c:(.text+0xe1): undefined reference to `xcb_wait_for_event'
/usr/bin/ld: monitor_watcher.c:(.text+0xfc): undefined reference to `xcb_disconnect'

@mafrasi2
Copy link
Author

mafrasi2 commented May 5, 2024

Hmm, have you linked with libxcb? For example like this:

$ gcc main.c -o main -lxcb -lxcb-randr -O2

On Ubuntu, you'll need to install libxcb-randr0-dev, libxcb1 and libxcb1-dev before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment