How can I get the active screen dimensions?

C#Wpf

C# Problem Overview


What I am looking for is the equivalent of System.Windows.SystemParameters.WorkArea for the monitor that the window is currently on.

Clarification: The window in question is WPF, not WinForm.

C# Solutions


Solution 1 - C#

Screen.FromControl, Screen.FromPoint and Screen.FromRectangle should help you with this. For example in WinForms it would be:

class MyForm : Form
{
  public Rectangle GetScreen()
  {
    return Screen.FromControl(this).Bounds;
  }
}

I don't know of an equivalent call for WPF. Therefore, you need to do something like this extension method.

static class ExtensionsForWPF
{
  public static System.Windows.Forms.Screen GetScreen(this Window window)
  {
    return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);
  }
}

Solution 2 - C#

You can use this to get desktop workspace bounds of the primary screen:

System.Windows.SystemParameters.WorkArea

This is also useful for getting just the size of the primary screen:

System.Windows.SystemParameters.PrimaryScreenWidth System.Windows.SystemParameters.PrimaryScreenHeight

Solution 3 - C#

Also you may need:

to get the combined size of all monitors and not one in particular.

Solution 4 - C#

Adding a solution that doesn't use WinForms but NativeMethods instead. First you need to define the native methods needed.

public static class NativeMethods
{
	public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;
	public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;


	[DllImport( "user32.dll" )]
	public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );


	[DllImport( "user32.dll" )]
	public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );


	[Serializable, StructLayout( LayoutKind.Sequential )]
	public struct NativeRectangle
	{
		public Int32 Left;
		public Int32 Top;
		public Int32 Right;
		public Int32 Bottom;


		public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )
		{
			this.Left = left;
			this.Top = top;
			this.Right = right;
			this.Bottom = bottom;
		}
	}


	[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]
	public sealed class NativeMonitorInfo
	{
		public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );
		public NativeRectangle Monitor;
		public NativeRectangle Work;
		public Int32 Flags;
	}
}

And then get the monitor handle and the monitor info like this.

		var hwnd = new WindowInteropHelper( this ).EnsureHandle();
		var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );

		if ( monitor != IntPtr.Zero )
		{
			var monitorInfo = new NativeMonitorInfo();
			NativeMethods.GetMonitorInfo( monitor, monitorInfo );

			var left = monitorInfo.Monitor.Left;
			var top = monitorInfo.Monitor.Top;
			var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );
			var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );
		}

Solution 5 - C#

Add on to ffpf

Screen.FromControl(this).Bounds

Solution 6 - C#

Beware of the scale factor of your windows (100% / 125% / 150% / 200%). You can get the real screen size by using the following code:

SystemParameters.FullPrimaryScreenHeight
SystemParameters.FullPrimaryScreenWidth

Solution 7 - C#

I wanted to have the screen resolution before opening the first of my windows, so here a quick solution to open an invisible window before actually measuring screen dimensions (you need to adapt the window parameters to your window in order to ensure that both are openend on the same screen - mainly the WindowStartupLocation is important)

Window w = new Window();
w.ResizeMode = ResizeMode.NoResize;
w.WindowState = WindowState.Normal;
w.WindowStyle = WindowStyle.None;
w.Background = Brushes.Transparent;
w.Width = 0;
w.Height = 0;
w.AllowsTransparency = true;
w.IsHitTestVisible = false;
w.WindowStartupLocation = WindowStartupLocation.Manual;
w.Show();
Screen scr = Screen.FromHandle(new WindowInteropHelper(w).Handle);
w.Close();
            

Solution 8 - C#

I needed to set the maximum size of my window application. This one could changed accordingly the application is is been showed in the primary screen or in the secondary. To overcome this problem e created a simple method that i show you next:

/// <summary>
/// Set the max size of the application window taking into account the current monitor
/// </summary>
public static void SetMaxSizeWindow(ioConnect _receiver)
{
    Point absoluteScreenPos = _receiver.PointToScreen(Mouse.GetPosition(_receiver));

    if (System.Windows.SystemParameters.VirtualScreenLeft == System.Windows.SystemParameters.WorkArea.Left)
    {
        //Primary Monitor is on the Left
        if (absoluteScreenPos.X <= System.Windows.SystemParameters.PrimaryScreenWidth)
        {
            //Primary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
        }
        else
        {
            //Secondary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
        }
    }

    if (System.Windows.SystemParameters.VirtualScreenLeft < 0)
    {
        //Primary Monitor is on the Right
        if (absoluteScreenPos.X > 0)
        {
            //Primary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
        }
        else
        {
            //Secondary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
        }
    }
}

Solution 9 - C#

This is a "Center Screen DotNet 4.5 solution", using SystemParameters instead of System.Windows.Forms or My.Compuer.Screen: Since Windows 8 has changed the screen dimension calculation, the only way it works for me looks like that (Taskbar calculation included):

Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
	Dim BarWidth As Double = SystemParameters.VirtualScreenWidth - SystemParameters.WorkArea.Width
    Dim BarHeight As Double = SystemParameters.VirtualScreenHeight - SystemParameters.WorkArea.Height
	Me.Left = (SystemParameters.VirtualScreenWidth - Me.ActualWidth - BarWidth) / 2
	Me.Top = (SystemParameters.VirtualScreenHeight - Me.ActualHeight - BarHeight) / 2         
End Sub
     

Center Screen WPF XAML

Solution 10 - C#

in C# winforms I have got start point (for case when we have several monitor/diplay and one form is calling another one) with help of the following method:

private Point get_start_point()
    {
        return
            new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,
                      Screen.GetBounds(parent_class_with_form.ActiveForm).Y
                      );
    }

Solution 11 - C#

WinForms

For multi-monitor setups you will also need account for the X and Y position:

Rectangle activeScreenDimensions = Screen.FromControl(this).Bounds;
this.Size = new Size(activeScreenDimensions.Width + activeScreenDimensions.X, activeScreenDimensions.Height + activeScreenDimensions.Y);

Solution 12 - C#

This debugging code should do the trick well:

You can explore the properties of the Screen Class

Put all displays in an array or list using Screen.AllScreens then capture the index of the current display and its properties.

enter image description here

C# (Converted from VB by Telerik - Please double check)

        {
    List<Screen> arrAvailableDisplays = new List<Screen>();
    List<string> arrDisplayNames = new List<string>();

    foreach (Screen Display in Screen.AllScreens)
    {
        arrAvailableDisplays.Add(Display);
        arrDisplayNames.Add(Display.DeviceName);
    }

    Screen scrCurrentDisplayInfo = Screen.FromControl(this);
    string strDeviceName = Screen.FromControl(this).DeviceName;
    int idxDevice = arrDisplayNames.IndexOf(strDeviceName);

    MessageBox.Show(this, "Number of Displays Found: " + arrAvailableDisplays.Count.ToString() + Constants.vbCrLf + "ID: " + idxDevice.ToString() + Constants.vbCrLf + "Device Name: " + scrCurrentDisplayInfo.DeviceName.ToString + Constants.vbCrLf + "Primary: " + scrCurrentDisplayInfo.Primary.ToString + Constants.vbCrLf + "Bounds: " + scrCurrentDisplayInfo.Bounds.ToString + Constants.vbCrLf + "Working Area: " + scrCurrentDisplayInfo.WorkingArea.ToString + Constants.vbCrLf + "Bits per Pixel: " + scrCurrentDisplayInfo.BitsPerPixel.ToString + Constants.vbCrLf + "Width: " + scrCurrentDisplayInfo.Bounds.Width.ToString + Constants.vbCrLf + "Height: " + scrCurrentDisplayInfo.Bounds.Height.ToString + Constants.vbCrLf + "Work Area Width: " + scrCurrentDisplayInfo.WorkingArea.Width.ToString + Constants.vbCrLf + "Work Area Height: " + scrCurrentDisplayInfo.WorkingArea.Height.ToString, "Current Info for Display '" + scrCurrentDisplayInfo.DeviceName.ToString + "' - ID: " + idxDevice.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);
}

VB (Original code)

 Dim arrAvailableDisplays As New List(Of Screen)()
    Dim arrDisplayNames As New List(Of String)()

    For Each Display As Screen In Screen.AllScreens
        arrAvailableDisplays.Add(Display)
        arrDisplayNames.Add(Display.DeviceName)
    Next

    Dim scrCurrentDisplayInfo As Screen = Screen.FromControl(Me)
    Dim strDeviceName As String = Screen.FromControl(Me).DeviceName
    Dim idxDevice As Integer = arrDisplayNames.IndexOf(strDeviceName)

    MessageBox.Show(Me,
                    "Number of Displays Found: " + arrAvailableDisplays.Count.ToString & vbCrLf &
                    "ID: " & idxDevice.ToString + vbCrLf &
                    "Device Name: " & scrCurrentDisplayInfo.DeviceName.ToString + vbCrLf &
                    "Primary: " & scrCurrentDisplayInfo.Primary.ToString + vbCrLf &
                    "Bounds: " & scrCurrentDisplayInfo.Bounds.ToString + vbCrLf &
                    "Working Area: " & scrCurrentDisplayInfo.WorkingArea.ToString + vbCrLf &
                    "Bits per Pixel: " & scrCurrentDisplayInfo.BitsPerPixel.ToString + vbCrLf &
                    "Width: " & scrCurrentDisplayInfo.Bounds.Width.ToString + vbCrLf &
                    "Height: " & scrCurrentDisplayInfo.Bounds.Height.ToString + vbCrLf &
                    "Work Area Width: " & scrCurrentDisplayInfo.WorkingArea.Width.ToString + vbCrLf &
                    "Work Area Height: " & scrCurrentDisplayInfo.WorkingArea.Height.ToString,
                    "Current Info for Display '" & scrCurrentDisplayInfo.DeviceName.ToString & "' - ID: " & idxDevice.ToString, MessageBoxButtons.OK, MessageBoxIcon.Information)

Screens List

Solution 13 - C#

I Know it's an old question, but others may get some value from this

int formWidth = form.Width;
int formHeight = form.Height;
int formTop = form.Top;
int formLeft = form.Left;

Screen screen = Screen.PrimaryScreen;
Rectangle rect = screen.Bounds;
int screenWidth = rect.Width;
int screenHeight = rect.Height;
int screenTop = rect.Top;
int screenLeft = rect.Left;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchilltempView Question on Stackoverflow
Solution 1 - C#Jeff YatesView Answer on Stackoverflow
Solution 2 - C#PyttrollView Answer on Stackoverflow
Solution 3 - C#742View Answer on Stackoverflow
Solution 4 - C#R.RusevView Answer on Stackoverflow
Solution 5 - C#faultyView Answer on Stackoverflow
Solution 6 - C#aDoubleSoView Answer on Stackoverflow
Solution 7 - C#AndreView Answer on Stackoverflow
Solution 8 - C#Ricardo MagalhãesView Answer on Stackoverflow
Solution 9 - C#NasenbaerView Answer on Stackoverflow
Solution 10 - C#Oleg BashView Answer on Stackoverflow
Solution 11 - C#user3424480View Answer on Stackoverflow
Solution 12 - C#Daniel SantosView Answer on Stackoverflow
Solution 13 - C#HemmaRoyDView Answer on Stackoverflow