开发者

How to manage multiple display setting in Windows 7 programatically?

I need to change resolution, position, and select which one is the ma开发者_开发技巧in display, preferably in .NET.


I think you can do it using User32.dll api functions via P/Invoke.
See the avaiable functions.

Sample code:

[DllImport("User32.dll")]
static extern long ChangeDisplaySettings(ref DeviceMode lpDevMode, int dwflags);

[DllImport("User32.dll")]
static extern int EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DeviceMode lpDevMode);

[DllImport("User32.dll")]
static extern int EnumDisplayDevices(string lpDevice, int iDevNum, ref DisplayDevice lpDisplayDevice, int dwFlags);

Code for changing the Screen resolution:

//DisplayDevice is a wrapper ... you can find it [here](http://pinvoke.net/default.aspx/Structures/DISPLAY_DEVICE.html)
List<DisplayDevice> devices = new List<DisplayDevice>();

bool error = false;
//Here I am listing all DisplayDevices (Monitors)
for (int devId = 0; !error; devId++)
{
    try
    {
        DisplayDevice device = new DisplayDevice();
        device.cb = Marshal.SizeOf(typeof(DisplayDevice));
        error = EnumDisplayDevices(null, devId, ref device, 0) == 0;
        devices.Add(device);
    }
    catch (Exception)
    {
        error = true;
    }
}

List<DisplaySet> devicesAndModes = new List<DisplaySet>();

foreach (var dev in devices)
{
    error = false;
    //Here I am listing all DeviceModes (Resolutions) for each DisplayDevice (Monitors)
    for (int i = 0; !error; i++)
    {
        try
        {
            //DeviceMode is a wrapper. You can find it [here](http://pinvoke.net/default.aspx/Structures/DEVMODE.html)
            DeviceMode mode = new DeviceMode();
            error = EnumDisplaySettings(dev.DeviceName, -1 + i, ref mode) == 0;
            //Display 
            devicesAndModes.Add(new DisplaySet { DisplayDevice = dev, DeviceMode = mode });
        }
        catch (Exception ex)
        {
            error = true;
        }
    }
}

//Select any 800x600 resolution ...
DeviceMode d800x600 = devicesAndModes.Where(s => s.DeviceMode.dmPelsWidth == 800).First().DeviceMode;

//Apply the selected resolution ...
ChangeDisplaySettings(ref d800x600, 0);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜