The sample application provides a way to retrieve the size (width and height) of the given screen or monitor on which the WPF window is hosing.
It mainly applies when multiple monitors are connected and user wants to control the rendering of the content based on the screen resolution on which the window is hosting.
I had been trying in several ways to find out the hosting screen size of the WPF window to determine whether to render the content or not based on the screen resolution. As part of my experience, I have come to a situation that there are some WPF controls which are not able to render if the resolution of the screen is higher than 2k. So, I need to detect the hosting screen size and stop rendering these controls if it is more than 2K resolution.
Using the Code
Currently, there are no APIs provided by the .NET Framework to get the screen size of hosting window. There is a
System.Windows.Forms.Screen class which provides the screen bounds, but it doesn't provide the proper data when dpi (Dots per Inch) settings are modified.
In general, the dpi settings are set to 100% by default, but user can modify them to increase the dpi settings like 125%, 150%, etc.
In my sample application, there is a
comboBox which is bind to
System.WIndows.Forms.Screen.AllScreen. Whenever selection is changed, the text controls show the corresponding values for the selected screen.
private void ComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
var monitorInfo = (Screen) this.comboBox.SelectedItem;
this.txtHeight.Text = monitorInfo.WorkingArea.Height.ToString();
this.txtWidth.Text = monitorInfo.WorkingArea.Width.ToString();
this.txtHeight_Copy.Text = monitorInfo.Bounds.Height.ToString();
this.txtWidth_Copy.Text = monitorInfo.Bounds.Width.ToString();
var size = GetHostingScreenSize(monitorInfo.DeviceName);
this.txtHeightNative.Text = size.Height.ToString();
this.txtWidthNative.Text = size.Width.ToString();
private System.Windows.Size GetHostingScreenSize(string devicename)
var hdc = NativeMethods.CreateDC(devicename, "", "", IntPtr.Zero);
int DESKTOPVERTRES = NativeMethods.GetDeviceCaps(hdc, (int)DeviceCap.DESKTOPVERTRES);
int DESKTOPHORZRES = NativeMethods.GetDeviceCaps(hdc, (int)DeviceCap.DESKTOPHORZRES);
Refer to the screenshot below for more reference.
Points of Interest
Initially, I tried using the
Screen.Bounds properties to get the size of the monitor/screen. But this is not showing the modified values when screen resolution is modified. Then, I have used the
GetDeviceCaps() native method to get actual width and height of the screen with respect to modified screen resolution.
Refer to more details about
GetDeviceCaps() method at the below links: