VisualTreeHelper.HitTest Method (Visual, HitTestFilterCallback, HitTestResultCallback, HitTestParameters)

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Initiates a hit test on the specified Visual, with caller-defined HitTestFilterCallback and HitTestResultCallback methods.

Namespace:   System.Windows.Media
Assembly:  PresentationCore (in PresentationCore.dll)

public static void HitTest(
	Visual reference,
	HitTestFilterCallback filterCallback,
	HitTestResultCallback resultCallback,
	HitTestParameters hitTestParameters
)

Parameters

reference
Type: System.Windows.Media.Visual

The Visual to hit test.

filterCallback
Type: System.Windows.Media.HitTestFilterCallback

The method that represents the hit test filter callback value.

resultCallback
Type: System.Windows.Media.HitTestResultCallback

The method that represents the hit test result callback value.

hitTestParameters
Type: System.Windows.Media.HitTestParameters

The parameter value to hit test against.

The filterCallback parameter can be null, in which case it is ignored. If filterCallback is not null, it is invoked before resultCallback. resultCallback cannot be null.

System_CAPS_noteNote

It is possible for a hit test that starts in a 2D visual tree to return RayHitTestResult, which is a 3D hit test result object. Hit testing that starts in a 2D visual tree seamlessly extends into any defined 3D visual tree.

The following example shows how to use the HitTest method to hit test the objects within a Canvas.

// Respond to the right mouse button down event by setting up a hit test results callback.
private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    // Retrieve the coordinate of the mouse position.
    Point pt = e.GetPosition((UIElement)sender);

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

    // Set up a callback to receive the hit test result enumeration.
    VisualTreeHelper.HitTest(myCanvas, null,
        new HitTestResultCallback(MyHitTestResult),
        new PointHitTestParameters(pt));

    // Perform actions on the hit test results list.
    if (hitResultsList.Count > 0)
    {
        Console.WriteLine("Number of Visuals Hit: " + hitResultsList.Count);
    }
}
// Return the result of the hit test to the callback.
public HitTestResultBehavior MyHitTestResult(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 HitTestResultBehavior.Continue;
}

.NET Framework
Available since 3.0
Return to top
Show: