Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the Screen Resolution from a C# winform app?

Tags:

c#

winforms

How can I retrieve the screen resolution that my C# Winform App is running on?

like image 926
etoisarobot Avatar asked Mar 08 '10 16:03

etoisarobot


People also ask

How do I find my screen resolution in C++?

h> Display* disp = XOpenDisplay(NULL); Screen* scrn = DefaultScreenOfDisplay(disp); int height = scrn->height; int width = scrn->width; with the linker option -lX11 .

How do I get my screen resolution back to normal?

Right-click on the desktop of your computer and select "Screen resolution". Click the drop-down menu labeled "Resolution" and use the slider to select the desired screen resolution. Click "Apply".


2 Answers

Do you need just the area a standard application would use, i.e. excluding the Windows taskbar and docked windows? If so, use the Screen.WorkingArea property. Otherwise, use Screen.Bounds.

If there are multiple monitors, you need to grab the screen from your form, i.e.

Form myForm; Screen myScreen = Screen.FromControl(myForm); Rectangle area = myScreen.WorkingArea; 

If you want to know which is the primary display screen, use the Screen.Primary property. Also, you can get a list of screens from the Screen.AllScreens property.

like image 159
Paul Williams Avatar answered Sep 22 '22 20:09

Paul Williams


The given answer is correct, as far as it goes. However, when you have set your Text size to anything more than 125%, Windows (and .NET) start to fib about the size of the screen in order to do auto-scaling for you.

Most of the time, this is not an issue - you generally want Windows and .NET to do this. However, in the case where you really, truly need to know the actual count of pixels on the screen (say, you want to paint directly to the desktop DC), you can do the following. I've only tried this on Win10. YMMV on other Windows versions.

So far, this is the only way I've found to get true screen pixel count if you don't want to globally turn off DPI awareness in your app. Note that this example gets the Primary display size - you will need to modify this to get other screens.

[DllImport("User32.dll")] static extern IntPtr GetDC(IntPtr hwnd);  [DllImport("User32.dll")] static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);  [DllImport("gdi32.dll")] static extern int GetDeviceCaps(IntPtr hdc, int nIndex);  IntPtr primary = GetDC(IntPtr.Zero); int DESKTOPVERTRES = 117; int DESKTOPHORZRES = 118; int actualPixelsX = GetDeviceCaps(primary, DESKTOPHORZRES); int actualPixelsY = GetDeviceCaps(primary, DESKTOPVERTRES); ReleaseDC(IntPtr.Zero, primary); 
like image 45
entiat Avatar answered Sep 20 '22 20:09

entiat