How to get screen resolution using API in C#





3.00/5 (1 vote)
Geting screen resolution using API with the possibility to recognize virtual screens.
Introduction
This article describe how to get screen resolution using API functions.
Background
When you need screen resolution in .NET, you can use the Screen.AllScreens
property. It works fine, but sometimes you have virtual screens and using the SystemInformation.VirtualScreen
property, you can get the resolution, but you cannot recognize which screen is virtual. I tried to find it using WMI, but it stops working when you change the orientation to portrait - this screen is excluded from the list. The best way (for me) is to use API functions - just these two functions:
[DllImport("user32.dll")]
static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum,
ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);
[DllImport("user32.dll")]
public static extern bool EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);
Using this way you can get the rotation of the screen too. It was a long way for me to find it and I hope it helps you