如何在WPF中获得鼠标在屏幕上的位置?

Ziy*_*rov 14 .net c# wpf mouse-position c#-4.0

它在特定控件中工作,但它不能解决特定控件.

如何直接从屏幕上获取鼠标位置并独立于任何控件使用鼠标事件(没有平台调用)?

2需要点:

  1. 鼠标不在控件内但在屏幕上时的鼠标事件.
  2. 鼠标不在控件内但在屏幕上时的鼠标位置.

它应该在不使用Platform Invoke的情况下解决.

接下来两个不起作用:

System.Windows.Input.Mouse.GetPosition(this)
Run Code Online (Sandbox Code Playgroud)

不会将鼠标定位到特定控件.

System.Windows.Forms.Cursor.Position.X
Run Code Online (Sandbox Code Playgroud)

System.Windows.Forms.Cursor.Position 不起作用,因为它在WPF应用程序中没有类型,但它适用于Windows窗体应用程序.

IntelliSense获取System.Windows.Forms.Cursor.Position,但它没有获得任何类型的Position,因此我无法得到:

Position.X    
Position.Y
Run Code Online (Sandbox Code Playgroud)

Point pointToWindow = Mouse.GetPosition(this);

Point pointToScreen = PointToScreen(pointToWindow);
Run Code Online (Sandbox Code Playgroud)

不会将鼠标定位到特定控件.

Hos*_*Rad 13

使用MouseDown控件的事件你可以试试这个:

var point = e.GetPosition(this.YourControl);
Run Code Online (Sandbox Code Playgroud)

编辑: 您可以捕获鼠标事件到特定控件使用Mouse.Capture(YourControl);它将捕获鼠标事件,即使它不在该控件上.这是链接


Rah*_*thi 9

您可以使用PointToScreen

将表示Visual的当前坐标系的Point转换为屏幕坐标中的Point.

像这样的东西:

private void MouseCordinateMethod(object sender, MouseEventArgs e)
{
    var relativePosition = e.GetPosition(this);
    var point= PointToScreen(relativePosition);
    _x.HorizontalOffset = point.X;
    _x.VerticalOffset = point.Y;
}
Run Code Online (Sandbox Code Playgroud)

请注意Mouse.GetPosition返回一个Point,PointToScreen并将该点转换为屏幕坐标

编辑:

你可以使用Mouse.Capture(SepcificControl);.来自 MSDN

捕获指定元素的鼠标输入.