WPF中的屏幕分辨率问题?

时间:2010-02-10 10:52:01

标签: c# .net wpf screen resolution

我将在WPF中使用以下代码检测分辨率:

double height = System.Windows.SystemParameters.PrimaryScreenHeight;
double width = System.Windows.SystemParameters.PrimaryScreenWidth;

我的屏幕当前分辨率为1920 * 1200,但height为960.0,width为1536.0 !!!

它有什么问题?
提前谢谢。

8 个答案:

答案 0 :(得分:33)

请记住,所有WPF位置和大小都是浮点数,单位为1/96英寸。不是像素。这使您的窗口设计分辨率独立。做数学:身高= 960/96 = 10英寸。将视频适配器设置为120 DPI(120/96 = 125%):10 * 120 = 1200像素。宽度相同:1536/96 * 120 = 1920像素。

System.Windows.Forms以像素为单位工作。高度低于1050,因为它减去了任务栏的高度。但对于WPF,你总是希望使用1/96“,而不是像素。

答案 1 :(得分:24)

为了实现更强大的实施,您应该计算系统上的DPI因子并使用这些因子。正常DPI值为96,但某些监视器可能具有不同的值。请考虑您的代码可能在DPI值不同于96的监视器上运行。请考虑以下代码:

    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;

ScreenHeight和ScreenWidth的值应与您在显示器的“属性”窗口中看到的值相匹配。

答案 2 :(得分:1)

尝试SystemParameters.FullPrimaryScreenWidth和FullPrimaryScreenHeight,我相信在删除屏幕上的任务栏和其他桌面频带后,PrimaryScreenWidth和Height会返回可用客户端窗口的大小。

答案 3 :(得分:1)

请在加载Windows后调用此方法。

 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);
    }
}

答案 4 :(得分:0)

答案 5 :(得分:0)

如果选中“使用Windows XP样式DPI缩放”,则“Screen.PrimaryScreen.Bounds”的返回值是正确的。如果不是,则返回的值按DPI值(默认值)按比例缩小。

要查找“使用Windows XP样式DPI缩放”复选框,请在以下链接中展开“在非DPI设计的程序中使文本和屏幕项更清晰”链接: http://windows.microsoft.com/en-us/windows-vista/Make-the-text-on-your-screen-larger-or-smaller

答案 6 :(得分:0)

您可以使用它:

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;

答案 7 :(得分:-1)

尝试这些..我相信这可以纠正错误.....

System.Windows.Form1.Screen.PrimaryScreen.Bounds.Height; System.Windows.Form1.Screen.PrimaryScreen.Bounds.Widtht;