How to get the screen dimensions across all monitors in WPF
Posted by andrewmyhre on August 21, 2008
I seem to be needing this code in every WPF I start at the moment, so here it is in a nice reproducable form. You need to add references to System.Windows.Forms and System.Drawing in order to do this though. Shame that dependency is required – I don’t see how getting screen information is strictly related to forms, so it’d be cool to be able to do this without requiring the System.Windows.Forms reference.
Anyway, stick this somewhere in your app (I put it in the App class and assign it to a static member):
27 private static Rect GetTotalScreenArea()
28 {
29 Rect screenArea = new Rect();
30 foreach (Screen s in Screen.AllScreens)
31 {
32 if (s.Bounds.Height > screenArea.Height)
33 screenArea.Height = s.Bounds.Height;
34
35 screenArea.Width += s.Bounds.Width;
36 }
37 return screenArea;
38 }
So my App.xaml.cs looks like this:
1 using System;
2 using System.Collections.Generic;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Windows;
7 using System.Windows.Forms;
8
9 namespace MyProject
10 {
11 /// <summary>
12 /// Interaction logic for App.xaml
13 /// </summary>
14 public partial class App : Application
15 {
16 public static Rect TotalScreenArea;
17
18 protected override void OnStartup(StartupEventArgs e)
19 {
20 TotalScreenArea = GetTotalScreenArea();
21
22 base.OnStartup(e);
23 }
24
25 private static Rect GetTotalScreenArea()
26 {
27 Rect screenArea = new Rect();
28 foreach (Screen s in Screen.AllScreens)
29 {
30 if (s.Bounds.Height > screenArea.Height)
31 screenArea.Height = s.Bounds.Height;
32
33 screenArea.Width += s.Bounds.Width;
34 }
35 return screenArea;
36 }
37 }
38 }
gehho said
If you intend to know the width and height of the total screen size (i.e. all available screens), I think you could also use SystemParameters.VirtualScreenHeight and SystemParameters.VirtualScreenWidth.
Ben said
There is a lot of assomption.
Monitors are not always place horizontaly nor aligned…
Anyway, the idea is there.