我如何知道WPF窗口的监视器

tom*_*ene 43 .net c# wpf

在C#应用程序中,如何确定WPF窗口是在主监视器还是其他监视器中?

Mik*_*ord 28

如果窗口最大化,那么你不能依赖window.Left或window.Top,因为它们可能是最大化之前的坐标.但是你可以在所有情况下都这样做:

    var screen = System.Windows.Forms.Screen.FromHandle(
       new System.Windows.Interop.WindowInteropHelper(window).Handle);
Run Code Online (Sandbox Code Playgroud)

  • 我正在打开它打开的屏幕,而不是当前的屏幕. (7认同)

Ser*_*ier 9

到目前为止,其他答复都没有涉及WPF部分问题.这是我的看法.

WPF似乎没有公开在其他回复中提到的Windows窗体的Screen类中找到的详细屏幕信息.

但是,您可以在WPF程序中使用WinForms Screen类:

添加对System.Windows.Forms和的引用System.Drawing

var screen = System.Windows.Forms.Screen.FromRectangle(
  new System.Drawing.Rectangle(
    (int)myWindow.Left, (int)myWindow.Top, 
    (int)myWindow.Width, (int)myWindow.Height));
Run Code Online (Sandbox Code Playgroud)

请注意,如果你是一个挑剔的人,你可能已经注意到,在某些情况下,这个代码可能会有一个像素的右边和底部坐标,在某种情况下是双向int转换.但既然你是一个挑剔的人,你会非常乐意修改我的代码;-)

  • 它也不适用于非默认 DPI。特别是每个显示器的 DPI 不同。 (3认同)

R.R*_*sev 5

为此,您需要使用一些本机方法。

https://msdn.microsoft.com/en-us/library/windows/desktop/dd145064(v=vs.85).aspx

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

    [DllImport( "user32.dll" )]
    public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );
}
Run Code Online (Sandbox Code Playgroud)

然后您只需检查您的窗口是哪个监视器,哪个是主要监视器。像这样:

        var hwnd = new WindowInteropHelper( this ).EnsureHandle();
        var currentMonitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );
        var primaryMonitor = NativeMethods.MonitorFromWindow( IntPtr.Zero, NativeMethods.MONITOR_DEFAULTTOPRIMARY );
        var isInPrimary = currentMonitor == primaryMonitor;
Run Code Online (Sandbox Code Playgroud)


And*_*are -1

您可以使用该Screen.FromControl方法获取当前表单的当前屏幕,如下所示:

Screen screen = Screen.FromControl(this);
Run Code Online (Sandbox Code Playgroud)

然后您可以检查Screen.Primary当前屏幕是否为主屏幕。

  • WPF `Window` 不是 Forms `Control`,因此在这种情况下您不能使用 `Screen.FromControl(this)`。 (24认同)
  • 但是,您可以使用:Screen.FromHandle(new WindowInteropHelper(this).Handle); (21认同)