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)
到目前为止,其他答复都没有涉及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转换.但既然你是一个挑剔的人,你会非常乐意修改我的代码;-)
为此,您需要使用一些本机方法。
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
当前屏幕是否为主屏幕。