C# 如何知道WPF窗口在哪个监视器中

C# 如何知道WPF窗口在哪个监视器中,c#,.net,wpf,C#,.net,Wpf,在C#应用程序中,如何确定WPF窗口位于主监视器还是另一监视器中?您可以使用该方法获取当前窗体的当前屏幕,如下所示: Screen screen = Screen.FromControl(this); 然后,您可以检查当前屏幕是否为主屏幕。签出 还有一个有趣的解决方案: bool onPrimary = this.Bounds.IntersectsWith(Screen.PrimaryScreen.Bounds); 其中“this”是您申请的主要形式。到目前为止,其他可用的答复没有涉及问题的

在C#应用程序中,如何确定WPF窗口位于主监视器还是另一监视器中?

您可以使用该方法获取当前窗体的当前屏幕,如下所示:

Screen screen = Screen.FromControl(this);
然后,您可以检查当前屏幕是否为主屏幕。

签出
还有一个有趣的解决方案:

bool onPrimary = this.Bounds.IntersectsWith(Screen.PrimaryScreen.Bounds);

其中“this”是您申请的主要形式。

到目前为止,其他可用的答复没有涉及问题的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));

请注意,如果您是一个挑剔的人,您可能已经注意到,在某些双精度到整数转换的情况下,此代码的右坐标和下坐标可能相差一个像素。但既然你是个挑剔的人,你会非常乐意修改我的代码;-)

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

    var screen = System.Windows.Forms.Screen.FromHandle(
       new System.Windows.Interop.WindowInteropHelper(window).Handle);

为了做到这一点,您需要使用一些本机方法

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

        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;

很有可能两者都会出现。@Helen这个问题适用于Winforms,这是针对不同的WPF。WPF
窗口
不是表单
控件,因此在这种情况下不能使用
屏幕。FromControl(this)
。但是,您可以使用:Screen.FromHandle(new WindowInteropHelper(this).Handle);请注意,
myWindow.RestoreBounds
如果窗口在屏幕上向左或向右定位,则不会返回窗口的实际大小和位置。(Windows按钮+向左或向右箭头)在这种情况下,您应该使用myWindow.left、myWindow.right、myWindow.Width和myWindow.Height。我得到的是打开屏幕的位置,而不是当前屏幕。它也不适用于非默认DPI。特别是,不同的每个监视器DPI.R.Rusev是否返回监视器的hwn?那么如何使用该hwnd来知道监视器编号是什么?我指的是windows在显示配置上显示的数字。有一种方法可以获得那个数字,并知道运行我的wpf窗口的监视器的数量是多少?
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 );
}
        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;