方法很简单,就是把鼠标捕获到Border控件,然后用PointToScreen()方法把相对于控件的坐标转换为相对于屏幕的坐标:
// xaml示例代码片(TextBlock用于显示坐标)
<Border x:Name="CatchPoint">
<TextBlock x:Name="ShowPoint"
Text="按下鼠标左键并移动以获取坐标"
VerticalAlignment="Center"
HorizontalAlignment="Center"
FontSize="18"/>
Border>
// 后台代码(重点:Mouse.Capture()一定要放在鼠标左键按下的判断内,否则会因为监听鼠标移动事件而占用大量CPU资源)
CatchPoint.MouseMove += delegate (object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (Mouse.Captured == null) Mouse.Capture(CatchPoint);
ShowPoint.Text = PointToScreen(e.GetPosition(this)).ToString();
}
else
{
Mouse.Capture(null); // 释放鼠标捕获
ShowPoint.Text = "按下鼠标左键并移动以获取坐标";
}
};
编译后的效果如下,只要在Border范围内按下鼠标左键并移动就开始获取鼠标的位置了,即便是把鼠标指针移出窗口也没关系,松开鼠标左键停止捕捉:
源码下载:点此下载