XML<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<appcontextswitchoverrides value="Switch.System.Windows.DoNotScaleForDpiChanges=false">
</appcontextswitchoverrides></runtime>
<startup>
<supportedruntime version="v4.0.30319">
</supportedruntime></startup>
</configuration>
Other[assembly: System.Windows.Media.DisableDpiAwareness()]
Otherusing System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Runtime.InteropServices; // DllImport
using System.Diagnostics; // Debug
namespace WpfApplication8
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string libname);
[DllImport("kernel32.dll")]
private static extern void FreeLibrary(IntPtr hlib);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern IntPtr GetProcAddress(IntPtr hlib, string procname);
private delegate int ProcSetProcessDpiAwareness(int level);
private delegate void ProcSetProcessDPIAware();
static void Win7SetDPIAware()
{
IntPtr hUser32 = LoadLibrary("user32.dll");
if (hUser32 != IntPtr.Zero)
{
IntPtr addrSetProcessDPIAware = GetProcAddress(hUser32, "SetProcessDPIAware");
if (addrSetProcessDPIAware != IntPtr.Zero)
{
ProcSetProcessDPIAware SetProcessDPIAware =
(ProcSetProcessDPIAware)
Marshal.GetDelegateForFunctionPointer(addrSetProcessDPIAware,
typeof(ProcSetProcessDPIAware));
SetProcessDPIAware();
}
FreeLibrary(hUser32);
}
}
// 需要在AssemblyInfo.cs里面设置
// [assembly: System.Windows.Media.DisableDpiAwareness()]
static bool Win81SetDPIAware()
{
IntPtr hShcore = LoadLibrary("shcore.dll");
if (hShcore != IntPtr.Zero)
{
IntPtr addrSetProcessDpiAwareness = GetProcAddress(hShcore, "SetProcessDpiAwareness");
if (addrSetProcessDpiAwareness != IntPtr.Zero)
{
// Win8.1以上版本,支持多显示器DPI
ProcSetProcessDpiAwareness SetProcessDpiAwareness =
(ProcSetProcessDpiAwareness)
Marshal.GetDelegateForFunctionPointer(addrSetProcessDpiAwareness,
typeof(ProcSetProcessDpiAwareness));
Type t = typeof(Window);
var evt = t.GetEvent("DpiChanged");
if (evt != null)
{
// 4.6.2新版WPF,支持DPI响应
// 需在app.config里面设置
// <runtime>
// <appcontextswitchoverrides value="Switch.System.Windows.DoNotScaleForDpiChanges=false">
// </appcontextswitchoverrides></runtime>
if (SetProcessDpiAwareness(2) < 0)
{
Debug.WriteLine("SetProcessDpiAwareness(2) failed!");
}
else
{
Debug.WriteLine("SetProcessDpiAwareness(2) succeeded!");
}
}
else
{
// 旧版WPF,不支持DPI响应
SetProcessDpiAwareness(1);
}
FreeLibrary(hShcore);
return true;
}
else // 找不到SetProcessDpiAwareness
{
FreeLibrary(hShcore);
return false;
}
}
else // 找不到shcore.dll
{
return false;
}
}
static App()
{
if (!Win81SetDPIAware())
{
Win7SetDPIAware();
}
}
}
}
[修改于 9年5个月前 - 2016/04/10 19:27:45]