【发布时间】:2017-09-29 13:16:47
【问题描述】:
我正在开发一个应用程序,它将在屏幕上围绕用户的鼠标坐标绘制一个屏幕捕获框。我试图让它在多个显示器上工作。使用 Cursor.Position 我可以获得全局坐标并确定用户在哪个屏幕上,但是因为我收到的坐标是全局坐标而不是相对于它所在的监视器,所以我在将全局坐标转换为屏幕相对坐标时遇到了困难定位。
当显示器全部垂直排列时,我可以使用基本逻辑来获取相对坐标,但我不确定当显示器以独特的方式设置时如何解决问题(即并非所有显示器的尺寸都相同, 一个在两个垂直显示器的右侧等)
这是我目前所拥有的:
_screens = ScreenHelper.GetMonitorsInfo();
CursorPosition = Cursor.Position;
var currentDevice = Screen.FromPoint(CursorPosition);
if (!currentDevice.Primary)
{
// If the current screen is not the primary monitor, we need to calculate the cursor's current position relative to the screen.
//Find the position in the screens array that the cursor is located, then the position of the primary display.
var cursorIndex = _screens.IndexOf(_screens.Find(x => x.DeviceName == currentDevice.DeviceName));
var primaryIndex = _screens.IndexOf(_screens.Find(x => x.DeviceName == Screen.PrimaryScreen.DeviceName));
//Cursor is to the right of primary screen.
if (primaryIndex > cursorIndex)
{
for (int i = cursorIndex + 1; i <= primaryIndex; i++)
{
CursorPosition = new Point(CursorPosition.X - _screens[i].HorizontalResolution, CursorPosition.Y);
}
}
//Cursor is to the left of primary screen.
else
{
for (int i = cursorIndex - 1; i >= primaryIndex; i--)
{
CursorPosition = new Point(CursorPosition.X + _screens[i].HorizontalResolution, CursorPosition.Y);
}
}
}
public static List<DeviceInfo> GetMonitorsInfo()
{
_result = new List<DeviceInfo>();
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, MonitorEnum, IntPtr.Zero);
return _result;
}
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumDelegate lpfnEnum, IntPtr dwData);
我是其中的一部分,但我不确定如何考虑水平甚至对角相对显示器定位。如何有效地获取相对于光标当前所在屏幕的鼠标坐标?
【问题讨论】:
-
_screens是如何实例化的? -
KDecker,我更新了 OP 以包含该信息。
-
另外,我正在寻找相对于光标所在屏幕的坐标,而不仅仅是当前屏幕是哪个屏幕。
-
很难看出这些信息有什么用处。但是你只需要减去 Screen.Bounds.X 和 Y。
标签: c# multiple-monitors cursor-position