Skip to content

Instantly share code, notes, and snippets.

@OakNinja
Created May 9, 2019 18:59
Show Gist options
  • Select an option

  • Save OakNinja/611e421927c1edbb71b0993b445608ab to your computer and use it in GitHub Desktop.

Select an option

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.
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);
}
}
@OakNinja
Copy link
Author

OakNinja commented May 9, 2019

Example usage:

var dpiScale = DpiScale.CurrentDeviceDpiScaleX();

var expectedFontSize = 42;

int fontSize = Convert.ToInt32(expectedFontSize / dpiScale );

var font = new Font("Segoe UI Emoji", fontSize);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment