将屏幕.PrimaryScreen.WorkingArea转换为更高DPI设置下的WPF尺寸

9

我在我的WPF应用程序中有以下函数,用于将窗口大小调整为主屏幕的工作区(全屏幕减去任务栏):

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    int theHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
    int theWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;

    this.MaxHeight = theHeight;
    this.MinHeight = theHeight;
    this.MaxWidth = theWidth;
    this.MinWidth = theWidth;

    this.Height = theHeight;
    this.Width = theWidth;

    this.Top = 0;
    this.Left = 0;
}

只要机器的DPI设置为100%,这个功能就非常好用。 但是,如果他们将DPI设置得更高,则此功能无法正常工作,并且窗口会溢出屏幕。 我意识到这是因为WPF像素与“真实”屏幕像素不同,并且因为我正在使用WinForms属性来获取屏幕尺寸。
我不知道是否有WPF等效于Screen.PrimaryScreen.WorkingArea的方法。 是否有一些我可以使用的东西,无论DPI设置如何都能正常工作?
如果没有,那么我想我需要进行某种形式的缩放,但是我不确定应该按多少比例缩放。
如何修改我的函数以考虑不同的DPI设置?
顺便说一下,如果你想知道为什么我需要使用此函数而不是仅最大化窗口,那是因为它是一个无边框窗口(WindowStyle =“None”),如果您最大化此类型的窗口,则会覆盖任务栏。
3个回答

14

您可以从SystemParameters.WorkArea属性中获取转换后的工作区大小:

Top = 0;
Left = 0;
Width = System.Windows.SystemParameters.WorkArea.Width;
Height = System.Windows.SystemParameters.WorkArea.Height;

3

0
如果您想获取两个屏幕的尺寸,您可以使用以下方法:
var primaryScreen = 
   System.Windows.Forms
      .Screen
      .AllScreens
      .Where(s => s.Primary)
      .FirstOrDefault();

var secondaryScreen = 
   System.Windows.Forms
      .Screen
      .AllScreens
      .Where(s => !s.Primary)
      .FirstOrDefault();

在此之后,您可以通过使用相应的代码访问宽度、高度等。

primaryScreen.Bounds.Width

再见 ;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接