简体   繁体   中英

Metro App - Getting the absolute pointer position of touch / mouse using C# / VB

I have been trying to do this but I am not successful.

I have a stackpanel with a textblock in my metro app page and a grid (named : grdTheHelper, placed outside the grid) with backcolor as BLACK (so that it is visible when brought inside the page)

My requirement is that when I touch / click on the textblock in the stackpanel, the black grid takes comes exactly where I clicked.

How is this possible. I tried

 Dim XY As New TranslateTransform

  Private Sub MainPage_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    grdTheHelper.RenderTransform = XY
  End Sub

 Private Sub txt1_Tapped(sender As Object, e As TappedRoutedEventArgs) Handles txt1.Tapped
         Dim AbsXY As Point
         AbsXY = e.GetPosition(Me)
         XY.X = AbsXY.X
         XY.Y = AbsXY.Y
    End Sub

But this is placing the grid say a bit too much far from where I have touched. I am clueless. Am I doing anything wrong? Is TranslateTransform only for moving the object by handling ManipulationDelta? Should Something else be used? Please help me.

If you have XAML like this:

<Rectangle x:Name="Rect1" Fill="White" Height="100" Width="100" />

<Rectangle x:Name="Rect2" Fill="Green" Height="100" Width="100" 
            ManipulationMode="All"
            ManipulationDelta="Rect2_ManipulationDelta_1">
    <Rectangle.RenderTransform>
        <CompositeTransform x:Name="Rect2Transform" />
    </Rectangle.RenderTransform>
</Rectangle>

And code like this:

private void Rect2_ManipulationDelta_1(object sender, ManipulationDeltaRoutedEventArgs e)
{
    Rect2Transform.TranslateX += e.Delta.Translation.X;
    Rect2Transform.TranslateY += e.Delta.Translation.Y;

    var _Visual = Rect2.TransformToVisual(this);
    var _Location = _Visual.TransformPoint(new Point());

    Rect1.SetValue(Canvas.LeftProperty, _Location.X);
    Rect1.SetValue(Canvas.TopProperty, _Location.Y - 100);
}

In the code above, I keep rect2 wherever the pointer currently is on the screen. And that method then puts rect1 directly above the new position of rect2.

This demonstrates EXACTLY how to get the absolute position from either a pointer device OR relative to an object on the screen. This is the answer to your question!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM