Monday, May 17, 2010

How to get the DependencyObject under the mouse cursor?

With help of VisualTreeHelper and its HitTest() methods, we can easily find the DependencyObject under the mouse cursor. Use the following code snippet to achieve this.

    List<DependencyObject> hitTestList = null;

    //Raised When Mouse is entered inside Panel
    private void Panel_MouseEnter(object sender, MouseEventArgs e)
        hitTestList = new List<DependencyObject>();       

        Point pt = e.GetPosition(sender as IInputElement);       

            sender as Visual, null,
            new PointHitTestParameters(pt));       


        DependencyObject elementToFind = null;
        foreach (DependencyObject element in hitTestList)
            if (element.GetType().Name.Equals("ElementToFind"))
                elementToFind = element;
                // ...
                // ...

    HitTestResultBehavior CollectAllVisuals_Callback(HitTestResult result)
        if (result == null || result.VisualHit == null)
            return HitTestResultBehavior.Stop;

        return HitTestResultBehavior.Continue;

Drop me a comment if you have any queries.
Post a Comment