Home > DeveloperSection > Forums > Check if a target was not hit in WPF
ben reitman
ben reitman

Total Post:96

Points:676
Posted on    November-14-2014 10:37 PM

 WPF C# 
Ratings:


 1 Reply(s)
 606  View(s)
Rate this:

I'm using the code below to see when the mouse right button is clicked, if it hits a target (Drawing) or not.

Now If the mouse hits the target a message will be shown stating that we hit the target.

But where can I show a message that the target was NOT hit? VisualTreeHelper.HitTest() doesn't seem to return a value indicating that the target was hit or not.

private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)

{

    var x = MousePos.RightDown.X;

    var y = MousePos.RightDown.Y;

    var hitRect = new Rect(x - 2, y - 2, 4, 4);

    var geom = new RectangleGeometry(hitRect);

    VisualTreeHelper.HitTest(Drawing,

                             null,

                             MyCallback,

                             new GeometryHitTestParameters(geom));

}

private HitTestResultBehavior MyCallback(HitTestResult result)

{

    MessageBox.Show("You hit the target");

    return HitTestResultBehavior.Stop;

}



Alex Leblois
Alex Leblois

Total Post:67

Points:471
Posted on    November-15-2014 3:13 AM

Have some class level flag to indicate whether hit is successful or not. Set the flag to true from MyCallback and show message based on that flag.

bool isTargetHit;   

private void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)

{

    isTargetHit = false;

    .......

    VisualTreeHelper.HitTest(Drawing,

                             null,

                             MyCallback,

                             new GeometryHitTestParameters(geom));

 

    if(isTargetHit)

    {

        MessageBox.Show("You hit the target");

    }

    else

    {

        MessageBox.Show("You did not hit the target");

    }

}

private HitTestResultBehavior MyCallback(HitTestResult result)

{

    isTargetHit = true;

    return HitTestResultBehavior.Stop;

}


Don't want to miss updates? Please click the below button!

Follow MindStick