在C#应用程序中,我如何确定一个WPF窗口是在主监视器还是另一个监视器中?
如果窗口被最大化,那么你不能完全依赖window.Left或者window.Top,因为它们可能是窗口最大化之前的坐标。但是在所有情况下,你可以采用以下方法:
var screen = System.Windows.Forms.Screen.FromHandle(
new System.Windows.Interop.WindowInteropHelper(window).Handle);
目前其他回复似乎并未涉及到问题中的WPF部分,以下是我的见解:
与其他回复中提到的Windows Forms的Screen类所包含的详细屏幕信息不同,WPF似乎没有暴露这方面的内容。
不过,在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));
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 );
}
然后,您只需检查窗口在哪个显示器上以及哪个是主要显示器。如下:
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;
*/
}
myWindow.RestoreBounds
不会返回窗口的真实大小和位置。在这种情况下,您应该使用myWindow.Left
、myWindow.Right
、myWindow.Width
和 myWindow.Height
。 - Renéif (Screen.AllScreens.Length < 2)
{
Console.WriteLine("You have just one monitor!");
return;
}
string primaryMonitor = "";
string currentMonitor = Screen.FromHandle(new WindowInteropHelper(this).Handle).DeviceName;
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
if (Screen.AllScreens[i].Primary == true)
{
primaryMonitor = Screen.AllScreens[i].DeviceName;
}
}
if (currentMonitor == primaryMonitor)
{
Console.WriteLine($"Window is in primary monitor ({primaryMonitor})");
}
else
{
Console.WriteLine($"Window is in ({currentMonitor}) and primary monitor is ({primaryMonitor})");
}
然而,获取主显示器可能有更简短的方法。
请查看如何在C#中找到应用程序正在运行的屏幕
此外在双屏环境下运行应用程序有一个有趣的解决方案:
bool onPrimary = this.Bounds.IntersectsWith(Screen.PrimaryScreen.Bounds);
其中,“this”是您的应用程序的主要表单。
您可以使用 Screen.FromControl
方法来获取当前窗体的屏幕,如下所示:
Screen screen = Screen.FromControl(this);
然后,您可以检查 Screen.Primary
来查看当前屏幕是否为主屏幕。
Window
不是 Windows Forms 的 Control
,因此在这种情况下你不能使用 Screen.FromControl(this)
。 - cprcrack