HowTo Make .Net Desktop App DPI Aware
For a better desktop UI experience, it is necessary to have access to the current screen size and pixel density of the display (DPI), so that an application controls and text fonts can be adjusted as needed for good layout and presentation.
Here is a list of steps necessary to make a desktop application be dpi aware.
- Add DLL Import to Program
The following lines need to be added to the Program.cs of the Windows app.
[System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool SetProcessDPIAware(); - Make each form DPI aware
Add the following to each form’s constructor:
this.AutoScaleMode = AutoScaleMode.Font; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); -
Call DPI Aware Method
Add this method call before starting the main form:
if (Environment.OSVersion.Version.Major >= 6) SetProcessDPIAware(); -
Update App.config
The following needs to be added to the app.config file to make it DPI aware:
NOTE: The necessary section is highlighted in yellow.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/>
</startup>
<System.Windows.Forms.ApplicationConfigurationSection>
<add key="DpiAwareness" value="PerMonitorV2"/>
<add key="EnableWindowsFormsHighDpiAutoResizing" value="false"/>
</System.Windows.Forms.ApplicationConfigurationSection>
</configuration>
No Comments