How do I know what monitor a WPF window is in
If the window is maximized then you cannot rely on window.Left or window.Top at all since they may be the coordinates before it was maximized. But you can do this in all cases:
var screen = System.Windows.Forms.Screen.FromHandle(
new System.Windows.Interop.WindowInteropHelper(window).Handle);
Other replies available so far don't address the WPF part of the question. Here's my take.
WPF doesn't seem to expose detailed screen info as found in Windows Forms' Screen class mentioned in other replies.
However, you can use the WinForms Screen class in your WPF program:
Add references to System.Windows.Forms
and 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));
Note that if you are a nitpicker, you may have noted that this code could have right and bottom coordinates off by one pixel in some case of double to int conversions. But since you are a nitpicker, you will be more than happy to fix my code ;-)
In order to do that you need to use some native methods.
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 );
}
Then you simply check in which monitor your window is and which is the primary one. Like this:
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;
public static bool IsOnPrimary(Window myWindow)
{
var rect = myWindow.RestoreBounds;
Rectangle myWindowBounds= new Rectangle((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height);
return myWindowBounds.IntersectsWith(WinForms.Screen.PrimaryScreen.Bounds);
/* Where
using System.Drawing;
using System.Windows;
using WinForms = System.Windows.Forms;
*/
}