1. 应用程序清单文件
xml
<assembly xmlns="urn:schemas-microsoft-com:asm.v3" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<application>
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
</assembly>
2. 配置文件设置
xml
<System.Windows.Forms.ApplicationConfigurationSection>
<add key="DpiAwareness" value="PerMonitorV2" />
</System.Windows.Forms.ApplicationConfigurationSection>
<appSettings>
<add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
</appSettings>
3. 使用 Windows API
csharp
internal static class Program
{
[DllImport("user32.dll")]
public static extern bool SetProcessDPIAware();
[STAThread]
static void Main()
{
SetProcessDPIAware();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
4. 设置 Form 的 AutoScaleMode
csharp
public Form1()
{
AutoScaleMode = AutoScaleMode.Dpi;
InitializeComponent();
}
5. 使用 TableLayoutPanel 控件
6. 动态调整 DPI 设置
csharp
[DllImport("user32.dll")]
public static extern int SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT value);
public enum DPI_AWARENESS_CONTEXT
{
DPI_AWARENESS_CONTEXT_UNAWARE = 0,
DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = 1,
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = 2,
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = 3
}
// 在需要的时候调用
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
结论
往期精品推荐: