c# uwp pointer position

2019-04-13 07:58发布

In UWP I am trying to get position of pointer.

I have managed to do it with next Event:

    private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        PointerPoint point = e.GetCurrentPoint(mainGrid);
        var x = point.Position.X;
        var y = point.Position.Y;
    }

And with this way it will be fired all the time. So, I needed some property to get that position. I have found this:

var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;

But it doesn't always return correct position.

Any other property to get current mouse location?

3条回答
我命由我不由天
2楼-- · 2019-04-13 08:25
var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;

pointerPosition gives you the client coordinates which are the cursor position X & Y of the screen, not relative to your app Window.

So you just need to use Window.Current.Bounds to find the coordinates of your app Window first, and then -

var x = pointerPosition.X - Window.Current.Bounds.X;
var y = pointerPosition.Y - Window.Current.Bounds.Y;
查看更多
Emotional °昔
3楼-- · 2019-04-13 08:28

This works for me at my canvas:

 var x = e.GetCurrentPoint(canBackArea).Position.X;
 var y = e.GetCurrentPoint(canBackArea).Position.Y;
查看更多
叛逆
4楼-- · 2019-04-13 08:34
  1. Add PointerMoved event handlers through code

    mainGrid.PointerMoved += mainGrid_PointerMoved;
    
  2. Remove PointerMoved event handlers in the event handler

    mainGrid.PointerMoved -= mainGrid_PointerMoved;
    
  3. Then Get the pointer data in PointerMoved event handlers

    var x = e.GetCurrentPoint(mainGrid).Position.X;
    var y = e.GetCurrentPoint(mainGrid).Position.X;
    

Here is the entire code

private void GetPointerPosition()
{
    mainGrid.PointerMoved += mainGrid_PointerMoved;
}

private void MainStack_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    mainGrid.PointerMoved -= mainGrid_PointerMoved;
    var x = e.GetCurrentPoint(mainGrid).Position.X;
    var y = e.GetCurrentPoint(mainGrid).Position.X;
}

Learn more about Adding event handlers in code from here

查看更多
登录 后发表回答