1,调用windows系统函数
public class GetSreenScaleAPI
{
public const int HORZRES = 8;
public const int VERTRES = 10;
public const int LOGPIXELSX = 88;
public const int LOGPIXELSY = 90;
public const int DESKTOPVERTRES = 117;
public const int DESKTOPHORZRES = 118;
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr ptr);
[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(
IntPtr hdc, // handle to DC
int nIndex // index of capability
);
[DllImport("user32.dll", EntryPoint = "ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc); [DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
public static float GetSreenScale()
{
var hdc = GetDC(GetDesktopWindow());
int nWidth = GetDeviceCaps(hdc, DESKTOPHORZRES);
ReleaseDC(IntPtr.Zero, hdc);
float f_Scale = (float)nWidth / (float)SystemParameters.PrimaryScreenWidth;
return f_Scale;
}
}
定义完后时直接调用GetSreenScale;注:这种方式在界面启动时调用可以获取到准确的值,二次调用无效。
2,采样winform用法
const double DpiPercent = 96;
private double GetScreenScale()
{
var intPtr = new WindowInteropHelper(this).Handle;//获取当前窗口的句柄
var screen = Screen.FromHandle(intPtr);//获取当前屏幕
double scale = 0;
using (Graphics currentGraphics = Graphics.FromHwnd(intPtr))
{
double dpiXRatio = currentGraphics.DpiX / DpiPercent;
double dpiYRatio = currentGraphics.DpiY / DpiPercent;
scale = dpiXRatio; // dpiYRatio均可
}
return scale;
}
需要引用 using System.Windows.Forms; 注:同样,这种方式在界面启动时调用可以获取到准确的值,二次调用无效。
3,FormVisual
private double GetScreenScale()
{
double scale = 0;
PresentationSource presentationSource = PresentationSource.FromVisual(this);
if (presentationSource != null)
{
Matrix m = presentationSource.CompositionTarget.TransformToDevice;
double scaleX = m.M11;
double scaleY = m.M22;
scale = scaleX; // scaleY均可
}
return scale;
}
直接调用GetSreenScale; 注:这种方式在窗体未显化之前无法使用,程序运行期间反复可用。
4,VisualTreeHelper
double dpiScaleX = VisualTreeHelper.GetDpi(this).DpiScaleX;
double dpiScaleY = VisualTreeHelper.GetDpi(this).DpiScaleY;
以上2句使用其中任意一句即可; 注:在程序运行任何时间均可调用,反复可用。