WPF 禁止 阻止系统 DPI 缩放。固定分辨率,不跟随系统缩放。
用户想实现:界面dpi96 100%显示,但系统想放大到125%。
默认程序是也可以放大,但程序实际显示出的分辨率(显示的内容)变少了的,用户还不愿意。所以有了以下方法。
谢谢这哥们儿:https://www.cnblogs.com/RedSky/p/18242167
运行环境:
framework4.7.2 windows10 wpf
第一步:
app.manifest设置:
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
</windowsSettings>
</application>
第二步:
参考自:https://github.com/microsoft/WPF-Samples/blob/main/PerMonitorDPI/readme.md
App.config设置:
<appSettings>
<add key="EnableWindowsFormsHighDpiAutoResizing" value="false"/>
</appSettings>
<runtime>
<AppContextSwitchOverrides value = "Switch.System.Windows.DoNotScaleForDpiChanges=true"/>
</runtime>
第三步:
参考自:https://www.cnblogs.com/RedSky/p/18242167
protected override void OnStartup(StartupEventArgs e)
{
Assembly presentationCoreAssembly = Assembly.GetAssembly(typeof(System.Windows.PresentationSource));
// 2. 通过全限定名获取内部的 System.LocalAppContext 类
// 注意:必须使用 BindingFlags.NonPublic 才能获取到内部类型
Type localAppContextType = presentationCoreAssembly.GetType(
"System.LocalAppContext",
throwOnError: false,
ignoreCase: false
);
// 测试输出
if (localAppContextType != null)
{
Console.WriteLine($"成功获取类型: {localAppContextType.FullName}");
}
TypeUtil.InvokeMethod(null,
localAppContextType, "DefineSwitchDefault",//typeof(AppContext)
new Type[] { typeof(string), typeof(bool) },
new object[] { "Switch.System.Windows.DoNotScaleForDpiChanges", true });
// 1. 获取 WindowsBase 程序集
Assembly windowsBaseAssembly = Assembly.GetAssembly(typeof(System.Windows.Threading.Dispatcher));
// 2. 获取内部的 NativeMethods 类
Type nativeMethodsType = windowsBaseAssembly.GetType("MS.Win32.NativeMethods");
// 3. 获取内部的嵌套枚举 PROCESS_DPI_AWARENESS
// 注意:必须使用 BindingFlags.NonPublic 才能获取到内部类型
Type processDpiAwarenessType = nativeMethodsType.GetNestedType(
"PROCESS_DPI_AWARENESS",
BindingFlags.NonPublic
);
// 测试输出
if (processDpiAwarenessType != null)
{
Console.WriteLine($"成功获取类型: {processDpiAwarenessType.FullName}");
}
var v = processDpiAwarenessType.GetEnumValues().GetValue(0);
TypeUtil.SetProperty(null, typeof(HwndTarget), "ProcessDpiAwareness", v);
TypeUtil.SetProperty(null, typeof(HwndTarget), "AppManifestProcessDpiAwareness", v);
base.OnStartup(e);
}
试成功了告诉我哦,评论点赞啥的都行。让我知道帮到了你就行。

浙公网安备 33010602011771号