public
Created

Toggle primary display using XRandr

  • Download Gist
toggle-primary.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/*
Copyright 2012, Jarkko Oranen
 
Redistribution, modification and use in any form is permitted
Use at your own risk. I will take no responsibility.
*/
 
// gcc -std=c99 -lXrandr toggle_primary.c -o toggle-primary
 
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
 
 
Display* dpy = NULL;
Window root = 0;
 
int main(int argc, char** argv) {
 
dpy = XOpenDisplay(NULL);
root = DefaultRootWindow(dpy);
XRRScreenResources* res = XRRGetScreenResources(dpy, root);
int num_connected = 0;
RROutput connected[res->noutput];
for (int i = 0; i < res->noutput; i++) {
XRROutputInfo* oinfo = XRRGetOutputInfo(dpy, res, res->outputs[i]);
if (oinfo->connection == RR_Connected) {
connected[num_connected] = res->outputs[i];
num_connected++;
}
XRRFreeOutputInfo(oinfo);
}
if (num_connected <= 1) {
goto exit;
}
for (int i = 0; i < num_connected; i++) {
if (XRRGetOutputPrimary(dpy, root) == connected[i]) {
XRRSetOutputPrimary(dpy, root, connected[(i+1) % num_connected]);
break;
}
}
 
exit:
XSync(dpy, 1);
XCloseDisplay(dpy);
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.