WPF正确处理屏幕位置

WPF可通过引用System.Windows.Forms来使用Screen.AllScreens获取屏幕信息,但是Screen.AllScreens获取的屏幕信息和物理屏幕有关,在Windows系统设置多屏幕之后会获取意想不到的屏幕位置,导致出现错误。下面先讲述如何引用System.Windows.Forms,然后介绍处理预期屏幕位置的方法。

1、.NetFramework引用System.Windows.Forms

右键“引用“节点选择”添加引用“,在弹出的”引用管理器“窗口找到”程序集-框架“,勾选”System.Windows.Forms “,点击”确定“按钮。

2、.Net5/.Net6引用System.Windows.Forms

右键项目名称,选择“编辑项目文件“,在”UseWPF“标签下添加:

<UseWindowsForms>true</UseWindowsForms>

3、获取预期的屏幕位置

Screen.AllScreens获取的屏幕信息和屏幕的物理位置有关,即和其连接在电脑的顺序有关;通常我们在具有多个屏幕时需要获取指定显示器的位置,那么将Screen.AllScreens的屏幕信息通过对其X坐标进行排序,就是我们希望得到的屏幕顺序,这样就避免了通过系统设置屏幕顺序带来的麻烦。

下面代码展示了如何将程序设置在第2个屏幕:

var allScreens = WinFormScreen.AllScreens.OrderBy(t => t.Bounds.Left).ToList();
var index = Math.Min(allScreens.Count - 1, 1);
var screen = allScreens[index];
Width = screen.Bounds.Width;
Height = screen.Bounds.Height;
Left = screen.Bounds.Left;
Top = screen.Bounds.Top;
posted @ 2022-09-19 19:32  xhubobo  阅读(576)  评论(0编辑  收藏  举报