Skip to content

Instantly share code, notes, and snippets.

@guihkx
Created May 26, 2021 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guihkx/c8b510d866a56cc1612b13657afef617 to your computer and use it in GitHub Desktop.
Save guihkx/c8b510d866a56cc1612b13657afef617 to your computer and use it in GitHub Desktop.
/**
* Compile it: gcc monitors.c -lX11 -lXrandr -Wall -Wextra -Werror -std=c89 -O3 -pedantic-errors -o monitors
* Run it: ./monitors
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
int main(void)
{
char *dpy;
Display *xdpy;
Window root;
XRRMonitorInfo *monitors;
int total;
int i;
char *m_name;
dpy = getenv("DISPLAY");
xdpy = XOpenDisplay(dpy);
if (!xdpy) {
fprintf(stderr, "Unable to open X display '%s': %s\n",
dpy, strerror(errno));
return 1;
}
root = DefaultRootWindow(xdpy);
monitors = XRRGetMonitors(xdpy, root, True, &total);
if (total == -1) {
fprintf(stderr, "XRRGetMonitors() failed: %s\n", strerror(errno));
XCloseDisplay(xdpy);
return 1;
}
printf("Number of connected monitors: %d\n", total);
for (i = 0; i < total; i++) {
m_name = XGetAtomName(xdpy, monitors[i].name);
printf("Monitor %d: %s%s\n", i + 1, m_name,
monitors[i].primary ? " (Primary)" : "");
XFree(m_name);
}
XRRFreeMonitors(monitors);
XCloseDisplay(xdpy);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment