判断Window在哪个屏幕

时间:2023-03-09 21:10:15
判断Window在哪个屏幕

最近在做窗口最大化时需要一个功能,如果是多个显示器的话,需要在当前显示器最大化,由于是根据屏幕长宽进行设置Window大小,没有使用WindowState.Maximized,window.Left不知道该设置多少。后来在调试时发现非主显示器的X坐标是根据主屏来的,如下图:第2个是主屏,那么第一个屏幕X就是-1600

判断Window在哪个屏幕

这样就可以根据Window.Left来计算所在屏幕

foreach (System.Windows.Forms.Screen screen in System.Windows.Forms.Screen.AllScreens)
{
if (winLeft >= screen.Bounds.Left && winLeft <= screen.Bounds.Left + screen.Bounds.Width)
{
return screen;
}
}
return System.Windows.Forms.Screen.AllScreens[0];

 后来发现一个更简答的方法

IntPtr handle = new WindowInteropHelper(window).Handle;
return System.Windows.Forms.Screen.FromHandle(handle);