简体   繁体   中英

Transform Screen.PrimaryScreen.WorkingArea to WPF dimensions at higher DPI settings

I have the following function in my WPF application that I use to resize a window to the primary screen's working area (the whole screen minus the taskbar):

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

This works very well, as long as the machine's DPI is set at 100%. However, if they have the DPI set higher, then this doesn't work, and the window spills off the screen. I realize that this is because WPF pixels aren't the same as "real" screen pixels, and because I'm using a WinForms property to get the screen dimensions.

I don't know of an WPF equivalent to Screen.PrimaryScreen.WorkingArea. Is there something I can use for this that would work regardless of DPI setting?

If not, then I guess I need to some sort of scaling, but I'm not sure how to determine how much to scale by.

How can I modify my function to account for different DPI settings?

By the way, in case you're wondering why I need to use this function instead of just maximizing the window, it's because it's a borderless window (WindowStyle="None"), and if you maximize this type of window, it covers the taskbar.

You get the transformed work area size from the SystemParameters.WorkArea property:

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

In WPF, you can use the SystemParameters.PrimaryScreenWidth and SystemParameters.PrimaryScreenHeight properties to find out the primary screen dimensions:

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

If you wanna get the dimensions of both Screens you simply can use:

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

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

After this you can reach Width, Height etc. by using

primaryScreen.Bounds.Width

So Long ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM