Home » Silverlight » How to do a hit test with Point and Shape?

How to do a hit test with Point and Shape?

In some situation, you may need to know if the mouse has hit a specific polygon drawn in a canvas. This can be easily done with Silverlight using the VisualTreeHelper.

First of all, you need to have a listener to the mouse even.

 void myCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
	e.Handled = true;
	Point currentMousePosition = e.GetPosition(this.myCanvas);
	var underMouseControls = GetControlFromCoordonate(currentMousePosition);
}

The second step is to create the method GetControlFromCoordonate to return a list of Control that has been clicked.

public IEnumerable<Control> GetControlFromCoordonate (Point coordonate)
{
	return VisualTreeHelper.FindElementsInHostCoordinates(coordonate, this.myCanvas).OfType<Control>();
}

This will return an enumeration of all UIElement which be cast to have only Control. You can even filter more if you search specific control.

So, the VisualTreeHelper may not have a HitTest method but with the FindElementsInHostCoordinates, you can filter the result to have the same result.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.