How To Do Hit Testing In WPF

You can use the following code to do hit testing on the objects of a canvas in WPF. By using this code you make sure to retrieve ALL objects of the hit testing at a given pixel position on the screen.


// The hit testing results
private List<DependencyObject> hitResultsList = new List<DependencyObject>();

// You need to set these variables for the hit testing:
// The point where you like to do the hit test, and the canvas with the objects you like to test on
private System.Windows.Point myPoint;
private Canvas myCanvas;

public void ExecuteHitTest()
{
  // Clear the contents of the list used for hit test results.
  hitResultsList.Clear();

  // Set up a callback to receive the hit test result enumeration.
  System.Windows.Media.VisualTreeHelper.HitTest(myCanvas,
      null,
      new System.Windows.Media.HitTestResultCallback(HitTestResult),
      new System.Windows.Media.PointHitTestParameters(myPoint));

  // Perform actions on the hit test results list.
  if (hitResultsList.Count > 0)
  {
    if ((hitResultsList[0].GetType() == typeof(System.Windows.Shapes.Ellipse)))
    {
      // insert your code here
    }
  }
}



public System.Windows.Media.HitTestResultBehavior HitTestResult(System.Windows.Media.HitTestResult result)
{
  // Add the hit test result to the list that will be processed after the enumeration.
  hitResultsList.Add(result.VisualHit);

  // Set the behavior to return visuals at all z-order levels.
  return System.Windows.Media.HitTestResultBehavior.Continue;
}