Created
May 9, 2019 18:59
-
-
Save OakNinja/611e421927c1edbb71b0993b445608ab to your computer and use it in GitHub Desktop.
WPF, Forms: Get the scaling/DPI scale factor on the device currently the application without the need of any UI elements using reflection. Useful for GDI stuff where you want to predict the composition.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static class DpiScale | |
| { | |
| private static readonly float WindowsDefaultDpi = 96.0f; | |
| private enum Axis {X, Y}; | |
| private static float GetScaleForAxis(Axis axis) | |
| { | |
| var axisProperty = axis == Axis.X ? "DpiX" : "Dpi"; | |
| var dpiProperty = typeof(SystemParameters).GetProperty(axisProperty, BindingFlags.NonPublic | BindingFlags.Static); | |
| var deviceDpi = (int)dpiProperty.GetValue(null, null); | |
| var dpiScale = deviceDpi / WindowsDefaultDpi; | |
| return dpiScale; | |
| } | |
| public static float CurrentDeviceDpiScaleX() | |
| { | |
| return GetScaleForAxis(Axis.X); | |
| } | |
| public static float CurrentDeviceDpiScaleY() | |
| { | |
| return GetScaleForAxis(Axis.Y); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: