Set Primary Display (ChangeDisplaySettingsEx)





5.00/5 (1 vote)
Simplified code for setting the primary display on a multi-monitor PC.
Introduction
I've seen plenty of "complicated" code for setting the "primary" display in a multiple display PC environment, but never a "simple" C# version. (This code is based off plenty of samples I've seen on the web.)
Background
This code originated out of the need to pop applications to multiple monitors during an automated start-up script (i.e., set a designated monitor as primary, start apps, then revert back to original monitor).
Using the code
The code is left raw for addition of "bells and whistles".
//manual gather - NewPrimary name ----------------------------------
WinApi.DISPLAY_DEVICE ddOne = new WinApi.DISPLAY_DEVICE();
ddOne.cb = Marshal.SizeOf(ddOne);
deviceID = 1;
WinApi.User_32.EnumDisplayDevices(null, deviceID, ref ddOne, 0);
string NewPrimary = ddOne.DeviceName;
WinApi.DEVMODE ndm6 = NewDevMode();
result = (WinApi.DisplaySetting_Results)WinApi.User_32.ChangeDisplaySettingsEx(NewPrimary,
ref ndm6, (IntPtr)null, (int)WinApi.DeviceFlags.CDS_SET_PRIMARY |
(int)WinApi.DeviceFlags.CDS_UPDATEREGISTRY, IntPtr.Zero);
Console.WriteLine("Action 3.2 result:" + result.ToString());