Search code examples
wpfdpi

Get Monitor dpi scale


I have a WPF application created in .NET 6 running on Windows 10

Given a system with two monitors, where one monitor is set to 100% scaling and the other is set to 200% scaling. How can I get the DPI scaling of the monitor the application window is currently on?

I've tried using VisualTreeHelper.GetDpi() where I pass in the window. But it always returns the scaling of the primary monitor (the one checked in 'Make this my main display' in the Windows 10 Display settings)


Solution

  • Add an app.manifest file to your application and turn on per monitor DPI awareness as examplified on GitHub:

    <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
        <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
        <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitor</dpiAwareness>
    </windowsSettings>
    </application>
    

    Then you should be able to get the DPI of the current monitor using the VisualTreeHelper.GetDpi API:

    VisualTreeHelper.GetDpi(this).PixelsPerDip