CHECK IF A TARGET WAS NOT HIT IN WPF

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
C# 
WPF
 1005  View(s)
Ratings:
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;

}

  1. Alex Leblois

    Post:67

    Points:471
    Re: Check if a target was not hit in WPF

    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;

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!