Programmatically rearranging displays

Most of my test machines and my laptop have a single display; but I have two dev machines which are each connected to two displays.

When I clean install Windows, I sometimes need to rearrange the displays:

swap-monitors

Since I clean install Windows frequently, I wrote myself a little C++ app which does this programmatically using EnumDisplayDevices / EnumDisplaySettings / ChangeDisplaySettingsEx.

Source and binaries attached.

Pseudocode:

for (each device returned by EnumDisplayDevices) {

   grab the position and the height/width using EnumDisplaySettings

}

calculate the desired position of the secondary monitor

Set it using ChangeDisplaySettingsEx with DM_POSITION

Call as:

>swapmonitors
Moved secondary monitor to (1920, 0)

EDIT: Oops: 0 should be CDS_GLOBAL | CDS_UPDATEREGISTRY, to make the settings apply to all users, and to persist across display resets / reboots

LONG status = ChangeDisplaySettingsEx(
    nameSecondary,
    &mode,
    nullptr, // reserved
    CDS_GLOBAL | CDS_UPDATEREGISTRY, // was 0
    nullptr // no video parameter
);

Browse source

Download swapmonitors.exe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s