Calculating Screen Resolutions Using WPF
- by Jeff Ferguson
WPF measures all elements in device independent pixels (DIPs). These DIPs equate to device pixels if the current display monitor is set to the default of 96 DPI. However, for monitors set to a DPI setting that is different than 96 DPI, then WPF DIPs will not correspond directly to monitor pixels.
Consider, for example, the WPF properties SystemParameters.PrimaryScreenHeight and SystemParameters.PrimaryScreenWidth. If your monitor resolution is set to 1024 pixels wide by 768 pixels high, and your monitor is set to 96 DPI, then WPF will report the value of SystemParameters.PrimaryScreenHeight as 768 and the value of SystemParameters.PrimaryScreenWidth as 1024. No problem. This aligns nicely because the WPF device independent pixel value (96) matches your monitor's DPI setting (96).
However, if your monitor is not set to display pixels at 96 DPI, then SystemParameters.PrimaryScreenHeight and SystemParameters.PrimaryScreenWidth will not return what you expect. The values returned by these properties may be greater than or less than what you expect, depending on whether or not your monitor's DPI value is less than or greater than 96. Since the SystemParameters.PrimaryScreenHeight and SystemParameters.PrimaryScreenWidth properties are WPF properties, their values are measured in WPF DIPs, rather than taking monitor DPI into effect. Once again: WPF measures all elements in device independent pixels (DIPs).
To combat this issue, you must take your monitor's DPI settings into effect if you're looking for the monitor's width and height using the monitor's DPI settings. The handy code block below will help you calculate these values regardless of the DPI setting on your monitor:
Window MainWindow = Application.Current.MainWindow;
PresentationSource MainWindowPresentationSource = PresentationSource.FromVisual(MainWindow);
Matrix m = MainWindowPresentationSource.CompositionTarget.TransformToDevice;
DpiWidthFactor = m.M11;
DpiHeightFactor = m.M22;
double ScreenHeight = SystemParameters.PrimaryScreenHeight * DpiHeightFactor;
double ScreenWidth = SystemParameters.PrimaryScreenWidth * DpiWidthFactor;
The values of ScreenHeight and ScreenWidth should, after this code is executed, match the resolution that you see in the display's Properties window.