Informatics, Uncategorized

Change your screen resolution from the command line

Today I’ve made a little program to quickly change the screen resolution from the command line. It’s written in C++, and can be downloaded from here. The source code looks like this:

// SetRes.cpp
// Aswin van Woudenberg
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
    int w;
    int h;
    int d;
    DEVMODE sDevMode;
    LONG rVal;
    if (argc!=4) {
        cout << "Usage: setres <width> <height> <depth>" << endl;
        return 1;
    }
    w = atoi(argv[1]);
    h = atoi(argv[2]);
    d = atoi(argv[3]);
    if (!w || !h || !d) {
        cout << "Invalid argument" << endl;
        return 1;
    }
    ZeroMemory(&sDevMode, sizeof(DEVMODE));
    sDevMode.dmSize = sizeof(DEVMODE);
    sDevMode.dmPelsWidth = w;
    sDevMode.dmFields |= DM_PELSWIDTH;
    sDevMode.dmPelsHeight = h;
    sDevMode.dmFields |= DM_PELSHEIGHT;
    sDevMode.dmBitsPerPel = d;
    sDevMode.dmFields |= DM_BITSPERPEL;
    rVal = ChangeDisplaySettings(&sDevMode, CDS_UPDATEREGISTRY);
    switch (rVal)
    {
        case DISP_CHANGE_SUCCESSFUL:
            rVal = SendMessage(HWND_BROADCAST, WM_DISPLAYCHANGE, SPI_SETNONCLIENTMETRICS, NULL);
            return 0;
        case DISP_CHANGE_RESTART:
            cout << "The computer must be restarted in order for the graphics mode to work." << endl;
            return 0;
        case DISP_CHANGE_BADFLAGS:
            cout << "An invalid set of flags was passed in." << endl;
            return 1;
        case DISP_CHANGE_FAILED:
            cout << "The display driver failed the specified graphics mode." << endl;
            return 1;
        case DISP_CHANGE_BADMODE:
            cout << "The graphics mode is not supported." << endl;
            return 1;
        case DISP_CHANGE_NOTUPDATED:
            cout << "Unable to write settings to the registry." << endl;
            return 0;
    }
    return 0;
}

Changing the resolution is done using the Win32 API ChangeDisplaySettings. After setting the resolution, running applications need to be notified which is done by calling SendMessage. The rest is pretty straightforward.

1 Comment

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*Required Fields