我将使用以下代码在WPF中检测分辨率:
double height = System.Windows.SystemParameters.PrimaryScreenHeight;
double width = System.Windows.SystemParameters.PrimaryScreenWidth;
我的屏幕当前分辨率为1920*1200,但是height
是960.0,width
是1536.0 !!!
有什么问题吗?
提前致谢。
我将使用以下代码在WPF中检测分辨率:
double height = System.Windows.SystemParameters.PrimaryScreenHeight;
double width = System.Windows.SystemParameters.PrimaryScreenWidth;
我的屏幕当前分辨率为1920*1200,但是height
是960.0,width
是1536.0 !!!
有什么问题吗?
提前致谢。
为了实现更加稳健的程序,您应该在系统上计算DPI因素并使用这些因素进行操作。正常DPI值为96,但某些显示器可能具有不同的值。要考虑到您的代码可能在具有不同DPI值的显示器上运行。考虑以下代码:
private static void CalculateDpiFactors()
{
Window MainWindow = Application.Current.MainWindow;
PresentationSource MainWindowPresentationSource = PresentationSource.FromVisual(MainWindow);
Matrix m = MainWindowPresentationSource.CompositionTarget.TransformToDevice;
thisDpiWidthFactor = m.M11;
thisDpiHeightFactor = m.M22;
}
然后您可以使用这些比率来获得最终值:
CalculateDpiFactors();
double ScreenHeight = SystemParameters.PrimaryScreenHeight * thisDpiHeightFactor;
double ScreenWidth = SystemParameters.PrimaryScreenWidth * thisDpiWidthFactor;
屏幕高度和宽度的值应该与您在显示器属性窗口中看到的相匹配。
public static class Ext
{
public static Size GetNativePrimaryScreenSize(this Window window)
{
PresentationSource mainWindowPresentationSource = PresentationSource.FromVisual(window);
Matrix m = mainWindowPresentationSource.CompositionTarget.TransformToDevice;
var dpiWidthFactor = m.M11;
var dpiHeightFactor = m.M22;
double screenHeight = SystemParameters.PrimaryScreenHeight * dpiHeightFactor;
double screenWidth = SystemParameters.PrimaryScreenWidth * dpiWidthFactor;
return new Size(screenWidth, screenHeight);
}
}
尝试使用 SystemParameters.FullPrimaryScreenWidth 和 FullPrimaryScreenHeight,我相信 PrimaryScreenWidth 和 Height 返回的是屏幕上除任务栏和其他桌面工具栏后可用客户端窗口的大小。
float dpiX, dpiY;
using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
{
dpiX = graphics.DpiX;
dpiY = graphics.DpiY;
}
double screenX = SystemParameters.PrimaryScreenWidth / 96 * dpiX;
double screenY = SystemParameters.PrimaryScreenHeight / 96 * dpiY;
尝试这些...我相信这可以纠正错误...
System.Windows.Form1.Screen.PrimaryScreen.Bounds.Height; System.Windows.Form1.Screen.PrimaryScreen.Bounds.Widtht;