Visual Studio 2019中替代重复添加app.manifest的永久解决方案
永久解决Windows窗体DPI缩放适配问题
当显示器缩放比例从175%调整为150%后,生成的窗体显示尺寸远大于设计器中的效果,你已经通过添加包含DPI感知配置的app.manifest解决了该问题,以下是无需每次为项目手动添加修改manifest的永久解决方案:
方案一:修改Visual Studio项目模板
找到Visual Studio对应版本的Windows窗体项目模板目录(以VS2022社区版为例,路径大致为C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\ProjectTemplates\CSharp\Windows\1033\WindowsFormsApp),将模板中的app.manifest替换为你已配置好的带<dpiAware>和<dpiAwareness>节点的版本。后续新建Windows窗体项目时,会自动继承该模板的manifest配置。
注意:修改模板需要管理员权限,不同VS版本、语言的模板路径可能存在差异。
方案二:通过代码全局配置DPI感知
在程序启动入口(Program.cs的Main方法)添加代码,在创建窗体前设置PerMonitorV2级别的DPI感知,无需依赖manifest文件:
using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace YourAppNamespace { static class Program { [DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(int dpiFlag); private const int DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4; [STAThread] static void Main() { // 启用PerMonitorV2 DPI感知 SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
后续新建项目时,直接复用这段启动代码即可自动适配DPI缩放。
方案三:系统级全局设置(不推荐)
通过修改注册表强制程序使用外部manifest,但该设置会影响系统中所有程序,可能导致老旧软件显示异常,仅适合个人开发环境临时使用:
- 打开注册表编辑器,定位到
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide - 新建DWORD值
PreferExternalManifest,将其值设置为1
内容的提问来源于stack exchange,提问作者Ingmar Helsmoortel
相关产品推荐
相关产品推荐

