如何获取光标位置并在跨显示器切换时触发PointerReleased函数
解决方案
首先明确:DisplayInformation.GetForCurrentView() 是用来获取当前应用窗口所在显示器的信息,而非光标所在的显示器,用它追踪跨显示器的光标切换完全不对路。你需要通过光标全局坐标判断其所属显示器,再对比切换状态触发目标事件。
下面是具体实现步骤:
1. 提前获取所有显示器的边界信息
先枚举系统中所有显示器的工作区域(考虑DPI缩放后的实际坐标),用DisplayManager来实现:
using Windows.Devices.Display.Core; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Input; private List<Rect> _displayBounds = new List<Rect>(); private int _currentDisplayIndex = -1; protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // 获取所有显示器的工作区域 var displayManager = DisplayManager.GetDefault(); foreach (var display in displayManager.GetCurrentDisplays()) { var view = display.GetCurrentView(); // 转换为全局屏幕坐标(适配DPI) var bounds = new Rect( view.Position.X, view.Position.Y, view.Size.Width, view.Size.Height ); _displayBounds.Add(bounds); } }
2. 在PointerMoved事件中追踪光标所在显示器
每次光标移动时,获取其全局坐标,判断所属显示器,和上一次记录对比:
private void Page_PointerMoved(object sender, PointerRoutedEventArgs e) { // 获取光标全局坐标 var pointerPoint = e.GetCurrentPoint(null); var globalPos = pointerPoint.Position; // 判断当前光标所在的显示器索引 int newDisplayIndex = -1; for (int i = 0; i < _displayBounds.Count; i++) { if (_displayBounds[i].Contains(globalPos)) { newDisplayIndex = i; break; } } // 如果显示器发生切换,且切换到第二显示器(索引需根据实际情况调整) if (newDisplayIndex != -1 && newDisplayIndex != _currentDisplayIndex) { if (newDisplayIndex == 1) // 假设第二显示器索引为1,可通过显示器IsPrimary属性判断主副 { // 触发PointerReleased事件 Page_PointerReleased(sender, null); } _currentDisplayIndex = newDisplayIndex; } // 你的原有PointerMoved逻辑 // ... }
3. 关键注意事项
- 显示器索引不一定固定为0(主)和1(副),可通过显示器的
IsPrimary属性明确主显示器,再确定目标副显示器。 - 若系统显示器布局变化(如插拔显示器),需监听
DisplayManager.DisplayChanged事件重新刷新_displayBounds列表。 - 若光标从应用窗口外切换到第二显示器时
PointerMoved不触发,可改用CoreWindow.PointerMoved监听全局光标移动。
内容的提问来源于stack exchange,提问作者odin_sanliveira
相关产品推荐
相关产品推荐

