100

を使用してプライマリ画面のサイズを取得できることを知っています

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

しかし、現在の画面のサイズを取得するにはどうすればよいですか?(マルチスクリーンユーザーは常にプライマリ画面を使用するとは限らず、すべての画面が同じ解像度を使用しているわけではありませんよね?)

XAMLからサイズにアクセスできると便利ですが、コード(C#)からアクセスするだけで十分です。

4

15 に答える 15

79

System.Windows.Formsから画面の周りに小さなラッパーを作成しましたが、現在はすべて機能しています...ただし、「デバイスに依存しないピクセル」についてはよくわかりません。

public class WpfScreen
{
    public static IEnumerable<WpfScreen> AllScreens()
    {
        foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
        {
            yield return new WpfScreen(screen);
        }
    }

    public static WpfScreen GetScreenFrom(Window window)
    {
        WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
        Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
        WpfScreen wpfScreen = new WpfScreen(screen);
        return wpfScreen;
    }

    public static WpfScreen GetScreenFrom(Point point)
    {
        int x = (int) Math.Round(point.X);
        int y = (int) Math.Round(point.Y);

        // are x,y device-independent-pixels ??
        System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
        Screen screen = System.Windows.Forms.Screen.FromPoint(drawingPoint);
        WpfScreen wpfScreen = new WpfScreen(screen);

        return wpfScreen;
    }

    public static WpfScreen Primary
    {
        get { return new WpfScreen(System.Windows.Forms.Screen.PrimaryScreen); }
    }

    private readonly Screen screen;

    internal WpfScreen(System.Windows.Forms.Screen screen)
    {
        this.screen = screen;
    }

    public Rect DeviceBounds
    {
        get { return this.GetRect(this.screen.Bounds); }
    }

    public Rect WorkingArea
    {
        get { return this.GetRect(this.screen.WorkingArea); }
    }

    private Rect GetRect(Rectangle value)
    {
        // should x, y, width, height be device-independent-pixels ??
        return new Rect
                   {
                       X = value.X,
                       Y = value.Y,
                       Width = value.Width,
                       Height = value.Height
                   };
    }

    public bool IsPrimary
    {
        get { return this.screen.Primary; }
    }

    public string DeviceName
    {
        get { return this.screen.DeviceName; }
    }
}
于 2010-01-22T17:05:51.087 に答える
26

ここでバディ。これにより、作業領域の幅と高さのみが表示されます

System.Windows.SystemParameters.WorkArea.Width
System.Windows.SystemParameters.WorkArea.Height
于 2013-09-09T18:33:47.473 に答える
19

これにより、ウィンドウの左上に基づいて現在の画面が表示されます。this.CurrentScreen()を呼び出すだけで、現在の画面の情報を取得できます。

using System.Windows;
using System.Windows.Forms;

namespace Common.Helpers
{
    public static class WindowHelpers
     {
        public static Screen CurrentScreen(this Window window)
         {
             return Screen.FromPoint(new System.Drawing.Point((int)window.Left,(int)window.Top));
         }
     }
}
于 2014-03-10T19:19:53.490 に答える
18

また、現在の画面のサイズ、特にタスクバーの幅を除いた長方形を返すワークエリアも必要でした。

これを使用して、マウスが配置されている場所まで右下に開いているウィンドウを再配置しました。ウィンドウはかなり大きいので、多くの場合、画面の境界から外れました。次のコードは@ejの回答に基づいています。これにより、現在の画面が表示されます。違いは、再配置アルゴリズムも示していることです。これが実際のポイントであると思います。

コード:

using System.Windows;
using System.Windows.Forms;

namespace MySample
{

    public class WindowPostion
    {
        /// <summary>
        /// This method adjust the window position to avoid from it going 
        /// out of screen bounds.
        /// </summary>
        /// <param name="topLeft">The requiered possition without its offset</param>
        /// <param name="maxSize">The max possible size of the window</param>
        /// <param name="offset">The offset of the topLeft postion</param>
        /// <param name="margin">The margin from the screen</param>
        /// <returns>The adjusted position of the window</returns>
        System.Drawing.Point Adjust(System.Drawing.Point topLeft, System.Drawing.Point maxSize, int offset, int margin)
        {
            Screen currentScreen = Screen.FromPoint(topLeft);
            System.Drawing.Rectangle rect = currentScreen.WorkingArea;

            // Set an offset from mouse position.
            topLeft.Offset(offset, offset);

            // Check if the window needs to go above the task bar, 
            // when the task bar shadows the HUD window.
            int totalHight = topLeft.Y + maxSize.Y + margin;

            if (totalHight > rect.Bottom)
            {
                topLeft.Y -= (totalHight - rect.Bottom);

                // If the screen dimensions exceed the hight of the window
                // set it just bellow the top bound.
                if (topLeft.Y < rect.Top)
                {
                    topLeft.Y = rect.Top + margin;
                }
            }

            int totalWidth = topLeft.X + maxSize.X + margin;
            // Check if the window needs to move to the left of the mouse, 
            // when the HUD exceeds the right window bounds.
            if (totalWidth > rect.Right)
            {
                // Since we already set an offset remove it and add the offset 
                // to the other side of the mouse (2x) in addition include the 
                // margin.
                topLeft.X -= (maxSize.X + (2 * offset + margin));

                // If the screen dimensions exceed the width of the window
                // don't exceed the left bound.
                if (topLeft.X < rect.Left)
                {
                    topLeft.X = rect.Left + margin;
                }
            }

            return topLeft;
        }
    }
}

いくつかの説明:

1) topLeft - position of the top left at the desktop (works                     
   for multi screens - with different aspect ratio).                            
            Screen1              Screen2                                        
        ─  ┌───────────────────┐┌───────────────────┐ Screen3                   
        ▲  │                   ││                   │┌─────────────────┐  ─     
        │  │                   ││                   ││   ▼-            │  ▲     
   1080 │  │                   ││                   ││                 │  │     
        │  │                   ││                   ││                 │  │ 900 
        ▼  │                   ││                   ││                 │  ▼     
        ─  └──────┬─────┬──────┘└──────┬─────┬──────┘└──────┬────┬─────┘  ─     
                 ─┴─────┴─            ─┴─────┴─            ─┴────┴─             
           │◄─────────────────►││◄─────────────────►││◄───────────────►│        
                   1920                 1920                1440                
   If the mouse is in Screen3 a possible value might be:                        
   topLeft.X=4140 topLeft.Y=195                                                 
2) offset - the offset from the top left, one value for both                    
   X and Y directions.                                                          
3) maxSize - the maximal size of the window - including its                     
   size when it is expanded - from the following example                        
   we need maxSize.X = 200, maxSize.Y = 150 - To avoid the expansion            
   being out of bound.                                                          

   Non expanded window:                                                         
   ┌──────────────────────────────┐ ─                                           
   │ Window Name               [X]│ ▲                                           
   ├──────────────────────────────┤ │                                           
   │         ┌─────────────────┐  │ │ 100                                       
   │  Text1: │                 │  │ │                                           
   │         └─────────────────┘  │ │                                           
   │                         [▼]  │ ▼                                           
   └──────────────────────────────┘ ─                                           
   │◄────────────────────────────►│                                             
                 200                                                            

   Expanded window:                                                             
   ┌──────────────────────────────┐ ─                                           
   │ Window Name               [X]│ ▲                                           
   ├──────────────────────────────┤ │                                           
   │         ┌─────────────────┐  │ │                                           
   │  Text1: │                 │  │ │                                           
   │         └─────────────────┘  │ │ 150                                       
   │                         [▲]  │ │                                           
   │         ┌─────────────────┐  │ │                                           
   │  Text2: │                 │  │ │                                           
   │         └─────────────────┘  │ ▼                                           
   └──────────────────────────────┘ ─                                           
   │◄────────────────────────────►│                                             
                 200                                                            
4) margin - The distance the window should be from the screen                   
   work-area - Example:                                                          
   ┌─────────────────────────────────────────────────────────────┐ ─            
   │                                                             │ ↕ Margin     
   │                                                             │ ─            
   │                                                             │              
   │                                                             │              
   │                                                             │              
   │                          ┌──────────────────────────────┐   │              
   │                          │ Window Name               [X]│   │              
   │                          ├──────────────────────────────┤   │              
   │                          │         ┌─────────────────┐  │   │              
   │                          │  Text1: │                 │  │   │              
   │                          │         └─────────────────┘  │   │              
   │                          │                         [▲]  │   │              
   │                          │         ┌─────────────────┐  │   │              
   │                          │  Text2: │                 │  │   │              
   │                          │         └─────────────────┘  │   │              
   │                          └──────────────────────────────┘   │ ─            
   │                                                             │ ↕ Margin     
   ├──────────────────────────────────────────────────┬──────────┤ ─            
   │[start] [♠][♦][♣][♥]                              │en│ 12:00 │              
   └──────────────────────────────────────────────────┴──────────┘              
   │◄─►│                                                     │◄─►│              
    Margin                                                    Margin            

* Note that this simple algorithm will always want to leave the cursor          
  out of the window, therefor the window will jumps to its left:                
  ┌─────────────────────────────────┐        ┌─────────────────────────────────┐
  │                  ▼-┌──────────────┐      │  ┌──────────────┐▼-             │
  │                    │ Window    [X]│      │  │ Window    [X]│               │
  │                    ├──────────────┤      │  ├──────────────┤               │
  │                    │       ┌───┐  │      │  │       ┌───┐  │               │
  │                    │  Val: │   │  │ ->   │  │  Val: │   │  │               │
  │                    │       └───┘  │      │  │       └───┘  │               │
  │                    └──────────────┘      │  └──────────────┘               │
  │                                 │        │                                 │
  ├──────────────────────┬──────────┤        ├──────────────────────┬──────────┤
  │[start] [♠][♦][♣]     │en│ 12:00 │        │[start] [♠][♦][♣]     │en│ 12:00 │
  └──────────────────────┴──────────┘        └──────────────────────┴──────────┘
  If this is not a requirement, you can add a parameter to just use             
  the margin:                                                                   
  ┌─────────────────────────────────┐        ┌─────────────────────────────────┐
  │                  ▼-┌──────────────┐      │                ┌─▼-───────────┐ │
  │                    │ Window    [X]│      │                │ Window    [X]│ │
  │                    ├──────────────┤      │                ├──────────────┤ │
  │                    │       ┌───┐  │      │                │       ┌───┐  │ │
  │                    │  Val: │   │  │ ->   │                │  Val: │   │  │ │
  │                    │       └───┘  │      │                │       └───┘  │ │
  │                    └──────────────┘      │                └──────────────┘ │
  │                                 │        │                                 │
  ├──────────────────────┬──────────┤        ├──────────────────────┬──────────┤
  │[start] [♠][♦][♣]     │en│ 12:00 │        │[start] [♠][♦][♣]     │en│ 12:00 │
  └──────────────────────┴──────────┘        └──────────────────────┴──────────┘
* Supports also the following scenarios:
  1) Screen over screen:
       ┌─────────────────┐  
       │                 │
       │                 │
       │                 │
       │                 │
       └─────────────────┘
     ┌───────────────────┐ 
     │                   │ 
     │  ▼-               │ 
     │                   │ 
     │                   │ 
     │                   │ 
     └──────┬─────┬──────┘ 
           ─┴─────┴─       
  2) Window bigger than screen hight or width
     ┌─────────────────────────────────┐        ┌─────────────────────────────────┐ 
     │                                 │        │ ┌──────────────┐                │
     │                                 │        │ │ Window    [X]│                │
     │                  ▼-┌────────────│─┐      │ ├──────────────┤ ▼-             │
     │                    │ Window    [│]│      │ │       ┌───┐  │                │
     │                    ├────────────│─┤ ->   │ │  Val: │   │  │                │ 
     │                    │       ┌───┐│ │      │ │       └───┘  │                │
     │                    │  Val: │   ││ │      │ │       ┌───┐  │                │
     │                    │       └───┘│ │      │ │  Val: │   │  │                │
     ├──────────────────────┬──────────┤ │      ├──────────────────────┬──────────┤
     │[start] [♠][♦][♣]     │en│ 12:00 │ │      │[start] [♠][♦][♣]     │en│ 12:00 │
     └──────────────────────┴──────────┘ │      └──────────────────────┴──────────┘
                          │       ┌───┐  │        │       └───┘  │
                          │  Val: │   │  │        └──────────────┘
                          │       └───┘  │
                          └──────────────┘


     ┌─────────────────────────────────┐             ┌─────────────────────────────────┐     
     │                                 │             │                                 │ 
     │                                 │             │ ┌───────────────────────────────│───┐
     │    ▼-┌──────────────────────────│────────┐    │ │ W▼-dow                        │[X]│
     │      │ Window                   │     [X]│    │ ├───────────────────────────────│───┤
     │      ├──────────────────────────│────────┤    │ │       ┌───┐      ┌───┐      ┌─┤─┐ │
     │      │       ┌───┐      ┌───┐   │  ┌───┐ │ -> │ │  Val: │   │ Val: │   │ Val: │ │ │ │
     │      │  Val: │   │ Val: │   │ Va│: │   │ │    │ │       └───┘      └───┘      └─┤─┘ │
     │      │       └───┘      └───┘   │  └───┘ │    │ └───────────────────────────────│───┘
     ├──────────────────────┬──────────┤────────┘    ├──────────────────────┬──────────┤
     │[start] [♠][♦][♣]     │en│ 12:00 │             │[start] [♠][♦][♣]     │en│ 12:00 │     
     └──────────────────────┴──────────┘             └──────────────────────┴──────────┘     
  • コード形式を使用する以外に選択肢はありませんでした(そうしないと、空白が失われてしまいます)。
  • もともとこれは上記のコードに<remark><code>...</code></remark>
于 2020-05-13T14:01:08.237 に答える
16

私の知る限り、現在のモニターのサイズを取得するためのネイティブWPF関数はありません。代わりに、ネイティブの複数のディスプレイモニター関数をPInvokeし、それらをマネージドクラスでラップして、XAMLからそれらを使用するために必要なすべてのプロパティを公開することができます。

于 2009-12-18T11:17:09.953 に答える
5

これだけ使ってみませんか?

var interopHelper = new WindowInteropHelper(System.Windows.Application.Current.MainWindow);
var activeScreen = Screen.FromHandle(interopHelper.Handle);
于 2016-12-15T09:14:12.917 に答える
4

時間をかけてSystemParametersメンバーをスキャンしてください。

  • VirtualScreenWidth
  • VirtualScreenHeight

これらは、画面の相対的な位置も考慮に入れています。

2台のモニターでのみテストされています。

于 2010-05-18T15:52:43.923 に答える
4

これは古い質問ですが、WPFはまだこれを「箱から出して」行うための優れた方法を提供しておらず、上記の回答は少し複雑すぎるように思われるため、以下の解決策が少し簡単に見つかることを願っています。消化する。

  • WPFに対応、つまり、デバイスに依存しない単位(WinFormスタイルのピクセルではない)を返します
  • さまざまなDPIのモニターをサポートします
  • 任意のサイズ/位置のタスクバーに対応
  • System.Windows.Windowの拡張メソッド。

楽しみ :)

using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using Point = System.Drawing.Point;

namespace ClrVpin.Shared
{
    public static class WindowExtensions
    {
        public static Rect GetCurrentScreenWorkArea(this Window window)
        {
            var screen = Screen.FromPoint(new Point((int) window.Left, (int) window.Top));
            var dpiScale = VisualTreeHelper.GetDpi(window);

            return new Rect {Width = screen.WorkingArea.Width / dpiScale.DpiScaleX, Height = screen.WorkingArea.Height / dpiScale.DpiScaleY};
        }
    }
}
于 2021-06-27T14:27:24.163 に答える
2

System.Windows.Formsクラスの使用に精通している場合は、System.Windows.Formsクラスの参照をプロジェクトに追加するだけです。

ソリューションエクスプローラー->参照->参照の追加...- > (アセンブリ:フレームワーク) ->下にスクロールして、System.Windows.Formsアセンブリ-> OKを確認します。

これで、System.Windows.Formsを使用して追加できます。以前と同じように、wpfプロジェクトで画面をステートメントして使用します。

于 2016-12-24T04:39:41.257 に答える
2

私はこの投稿に出くわし、私がやろうとしていたことを完全に捉えた答えはどれもなかったことがわかりました。私は3840x2160の解像度のラップトップと1920x1080の解像度の2台のモニターを持っています。WPFアプリケーションで正しいモニターサイズを取得するには、アプリケーションをDPI対応にする必要がありました。次に、Win32APIを使用してモニターサイズを取得しました。

これを行うには、最初にウィンドウを、サイズを取得したいモニターに移動します。次に、アプリケーションのMainWindowのhwnd(メインウィンドウである必要はありませんが、私のアプリケーションには1つのウィンドウしかない)とIntPtrをモニターに取得します。次に、MONITORINFOEX構造体の新しいインスタンスを作成し、GetMonitorInfoメソッドを呼び出しました。

MONITORINFOEX構造体には、作業領域と画面のフル解像度の両方があるため、必要なものを返すことができます。これにより、System.Windows.Formsへの参照を省略できるようになります(アプリケーションで他の何かが必要ない場合)。このソリューションを考え出すために、System.Windows.Forms.Screenの.NETFrameworkリファレンスソースを使用しました。

public System.Drawing.Size GetMonitorSize()
{
    var window = System.Windows.Application.Current.MainWindow;
    var hwnd = new WindowInteropHelper(window).EnsureHandle();
    var monitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST);
    NativeMethods.MONITORINFO info = new NativeMethods.MONITORINFO();
    NativeMethods.GetMonitorInfo(new HandleRef(null, monitor), info);
    return info.rcMonitor.Size;
}

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

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

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool GetMonitorInfo(HandleRef hmonitor, MONITORINFO info);
    
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
    public class MONITORINFO
    {
        internal int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
        internal RECT rcMonitor = new RECT();
        internal RECT rcWork = new RECT();
        internal int dwFlags = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;

        public RECT(int left, int top, int right, int bottom)
        {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

        public RECT(System.Drawing.Rectangle r)
        {
            left = r.Left;
            top = r.Top;
            right = r.Right;
            bottom = r.Bottom;
        }

        public static RECT FromXYWH(int x, int y, int width, int height) => new RECT(x, y, x + width, y + height);

        public System.Drawing.Size Size => new System.Drawing.Size(right - left, bottom - top);
    }
}
于 2021-02-01T20:17:59.050 に答える
1

私はその要求を理解しています。重要なのは、これらの値を取得するためのWPFメソッドがありますが、そうです、貢献者の1人は正しく、直接ではありません。解決策は、これらすべての回避策を取得することではなく、クリーンな設計と開発に従って初期アプローチを変更することです。

A)最初のメインウィンドウを画面に設定します

B)大量の便利なWPFメソッドを含むActualWindowの値を取得します

C)サイズ変更や最小化など、必要な動作に合わせてWindowsをいくつでも追加できますが、ロードおよびレンダリングされた画面にいつでもアクセスできるようになりました。

次の例に注意してください。そのようなアプローチを使用する必要があるコードがいくつかありますが、それは機能するはずです(画面の各コーナーのポイントが得られます):シングルでの作業例、デュアルモニターと異なる解像度(プライマルメインウィンドウクラス内):

InitializeComponent();
[…]
ActualWindow.AddHandler(Window.LoadedEvent, new RoutedEventHandler(StartUpScreenLoaded));

ルーティングされたイベント:

private void StartUpScreenLoaded(object sender, RoutedEventArgs e)
    {
        Window StartUpScreen = sender as Window;

        // Dispatcher Format B:
        Dispatcher.Invoke(new Action(() =>
        {
            // Get Actual Window on Loaded
            StartUpScreen.InvalidateVisual();
            System.Windows.Point CoordinatesTopRight = StartUpScreen.TranslatePoint(new System.Windows.Point((StartUpScreen.ActualWidth), (0d)), ActualWindow);
            System.Windows.Point CoordinatesBottomRight = StartUpScreen.TranslatePoint(new System.Windows.Point((StartUpScreen.ActualWidth), (StartUpScreen.ActualHeight)), ActualWindow);
            System.Windows.Point CoordinatesBottomLeft = StartUpScreen.TranslatePoint(new System.Windows.Point((0d), (StartUpScreen.ActualHeight)), ActualWindow);

            // Set the Canvas Top Right, Bottom Right, Bottom Left Coordinates
            System.Windows.Application.Current.Resources["StartUpScreenPointTopRight"] = CoordinatesTopRight;
            System.Windows.Application.Current.Resources["StartUpScreenPointBottomRight"] = CoordinatesBottomRight;
            System.Windows.Application.Current.Resources["StartUpScreenPointBottomLeft"] = CoordinatesBottomLeft;
        }), DispatcherPriority.Loaded);
    }
于 2019-05-07T10:59:31.267 に答える
1

フルスクリーンウィンドウ(を持っている)を使用する場合は、その内容を次のようWindowState = WindowState.Maximized, WindowStyle = WindowStyle.Noneにラップできます。System.Windows.Controls.Canvas

<Canvas Name="MyCanvas" Width="auto" Height="auto">
...
</Canvas>

次に、DPI設定を考慮に入れて、デバイスに依存しない単位で、を使用MyCanvas.ActualWidthして現在の画面の解像度を取得できます。MyCanvas.ActualHeight最大化されたウィンドウ自体のようにマージンは追加されません。

(CanvasはUIElementsを子として受け入れるため、どのコンテンツでも使用できるはずです。)

于 2019-11-18T15:40:40.673 に答える
-1

XAMLでウィンドウを画面の中央に配置してからWindowStartupLocation="CenterOwner"、WindowLoaded()を呼び出します。

double ScreenHeight = 2 * (Top + 0.5 * Height);

于 2019-08-20T19:31:05.377 に答える
-5
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenhight= System.Windows.SystemParameters.PrimaryScreenHeight;
于 2013-11-14T09:41:58.747 に答える
-5

それはで動作します

this.Width = System.Windows.SystemParameters.VirtualScreenWidth;
this.Height = System.Windows.SystemParameters.VirtualScreenHeight;

2台のモニターでテスト済み。

于 2016-03-21T06:57:32.457 に答える