changing screen resolution

As I’ve found many posts related to this, here is a little example:


  • This is a simple example on how to change screen resolution
  • under Linux/XFree86. No error checking.
  • Applications must be linked with -lX11 -lXxf86vm -lXext
  • by Julien Cayzac.


#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/extensions/xf86vmode.h>
using ::std::cerr;
using ::std::endl;

int main(void) {
// catch the current display and open it
Display* d = XOpenDisplay(0L);
if (d==0L) exit(1);

    // *UGLY* XF86VidModeModeInfo is equivalent to the struct below
    // "mode" declaration, but it might change someday...
    union {
            XF86VidModeModeInfo mode;
            struct {
                    int dotclock;
                    XF86VidModeModeLine line;
            } line_info;
    } old;

    // save the current mode into "old".
    XF86VidModeGetModeLine(d, DefaultScreen(d), &old.line_info.dotclock, &old.line_info.line);
    cerr << "Mode saved: ";
    cerr << old.mode.hdisplay << "x" << old.mode.vdisplay << endl;

    // get a list of all available video modes
    XF86VidModeModeInfo**   my_modes = 0L;
    int                     mode_count = 0;
    XF86VidModeGetAllModeLines(d, DefaultScreen(d), &mode_count, &my_modes);
    cerr << mode_count << " available modes:" << endl;
    for (int i=0; i<mode_count; i++) {
            cerr << "	" << my_modes[i]->hdisplay << "x"
            << my_modes[i]->vdisplay << endl;

    // set mode to the last available one (typically the lowest
    // resolution available)
    XF86VidModeSwitchToMode(d, DefaultScreen(d), my_modes[mode_count-1]);
    // IMPORTANT, as screen's resolution might not be changed otherwise.

    // sleep for ten seconds, so we can see the mode change.

    // switch back to old mode...
    XF86VidModeSwitchToMode(d, DefaultScreen(d), &old.mode);

    // All done
    return 0;


Hope it helps…


This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.