Как я могу получить активные размеры экрана? - PullRequest
128 голосов
/ 31 октября 2008

То, что я ищу, является эквивалентом System.Windows.SystemParameters.WorkArea для монитора, на котором в данный момент находится окно.

Уточнение: Это окно WPF, а не WinForm.

Ответы [ 10 ]

133 голосов
/ 31 октября 2008

Screen.FromControl, Screen.FromPoint и Screen.FromRectangle должны помочь вам в этом. Например, в WinForms это будет:

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

Я не знаю эквивалентного вызова для WPF. Поэтому вам нужно сделать что-то вроде этого метода расширения.

static class ExtensionsForWPF
{
  public static System.Windows.Forms.Screen GetScreen(this Window window)
  {
    return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);
  }
}
61 голосов
/ 13 апреля 2009

Вы можете использовать это для получения границ рабочего стола рабочего стола основного экрана:

System.Windows.SystemParameters.WorkArea

Это также полезно для получения только размера основного экрана:

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

33 голосов
/ 25 мая 2010

Также вам может понадобиться:

чтобы получить общий размер всех мониторов, а не одного конкретного.

15 голосов
/ 28 апреля 2016

Добавление решения, которое использует не WinForms, а NativeMethods. Сначала вам нужно определить необходимые нативные методы.

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

А затем получите дескриптор монитора и информацию о мониторе следующим образом.

        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 );
        }
12 голосов
/ 31 октября 2008

Добавить в ffpf

Screen.FromControl(this).Bounds
10 голосов
/ 14 ноября 2013

Остерегайтесь масштабного коэффициента ваших окон (100% / 125% / 150% / 200%). Вы можете получить реальный размер экрана, используя следующий код:

SystemParameters.FullPrimaryScreenHeight
SystemParameters.FullPrimaryScreenWidth
4 голосов
/ 04 сентября 2012

Я хотел иметь разрешение экрана перед открытием первого из моих окон, поэтому здесь быстрое решение, чтобы открыть невидимое окно перед фактическим измерением размеров экрана (вам необходимо адаптировать параметры окна к вашему окну, чтобы гарантировать, что оба открыты на одном экране - в основном WindowStartupLocation важно)

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();
3 голосов
/ 10 июля 2013

Мне нужно было установить максимальный размер моего оконного приложения. Это можно изменить в зависимости от приложения, которое было показано на основном экране или на дополнительном. Чтобы преодолеть эту проблему, я создал простой метод, который я покажу вам следующим:

/// <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;
        }
    }
}
2 голосов
/ 08 июля 2017

в C # winforms У меня есть начальная точка (для случая, когда у нас есть несколько мониторов / диплей и одна форма вызывает другую) с помощью следующего метода:

private Point get_start_point()
    {
        return
            new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,
                      Screen.GetBounds(parent_class_with_form.ActiveForm).Y
                      );
    }
2 голосов
/ 10 октября 2013

Это «Центр экрана Решение DotNet 4.5 », использующее Параметры системы вместо System.Windows.Forms или My.Compuer.Screen : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Пример расчета так, как это работает для меня (включая панель задач):

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...