Changing the screen resolution under Linux/XFree86

This is a simple example on how to change screen resolution under Linux/XFree86 (no error checking performed). Applications must be linked with libX11, libXxf86vm and libXext.

#include <cstdio>
#include <unistd.h>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/extensions/xf86vmode.h>
#include <iostream>
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 << "\t" << 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;
Powered by Blogger.