且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows 10 操作系统上的 Windows 窗体图形问题

更新时间:2023-02-22 17:51:30

要解决该问题,您可以使用以下任一选项使您的应用程序具有 DPI-Aware:

To solve the problem, you can make your application DPI-Aware using either of these options:

重要提示: 建议您设置进程默认 DPI通过应用程序清单而不是 API 调用进行感知.

Important Note: It is recommended that you set the process-default DPI awareness via application manifest, not an API call.

使用应用程序清单文件

要使应用程序具有 DPI 感知能力,您可以将一个应用程序清单文件添加到您的项目中.然后在 app.manifest 文件中,取消注释与 DPI-Awareness 相关的部分:

Using Application Manifest File

To make the application DPI-Aware, you can add an Application Manifest File to your project. Then in the app.manifest file, uncomment the part that is related to DPI-Awareness:

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

然后在您的 app.config 文件中,添加 EnableWindowsFormsHighDpiAutoResizing 将其值设置为 true:

Then in your app.config file, add EnableWindowsFormsHighDpiAutoResizing setting its value to true:

<appSettings>
  <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
</appSettings>

有关详细信息,请查看 Microsoft 文档中的以下主题:

For more information take a look at the following topic in Microsoft docs:

  • Windows 上的高 DPI 桌面应用程序开发

您可以在显示主窗体之前使用 SetProcessDPIAware() 方法来设置应用程序 dpi 感知并防止窗口缩放应用程序.此外,您应该检查 Windows 版本是否大于或等于 vista:

You can use SetProcessDPIAware() method before showing your main form to set your application dpi aware and prevent windows from scaling the application. Also you should check the windows version to be greater than or equals to vista:

static class Program
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern bool SetProcessDPIAware();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        if (Environment.OSVersion.Version.Major >= 6)
            SetProcessDPIAware();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(true);
        Application.Run(new Form1());
    }
}

注意事项

  1. 正如上面已经提到的,建议您通过应用程序清单而不是 API 调用来设置进程默认的 DPI 感知.

  1. As it's already mentioned above, it is recommended that you set the process-default DPI awareness via application manifest, not an API call.

在使用 API 调用之前,请阅读文档以了解支持的操作系统以及如果 DLL 在初始化期间缓存 dpi 设置时可能出现的竞争条件.还要记住,DLL 应该接受宿主进程的 dpi 设置,而不是 API 调用本身.

Before using API calls, read the documentations to know about supported OS and also possible race condition if a DLL caches dpi settings during initialization. Also keep in mind, DLLs should accept the dpi setting of the host process rather than API call themselves.