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);       

        VisualTreeHelper.HitTest(
            sender as Visual, null,
            CollectAllVisuals_Callback,
            new PointHitTestParameters(pt));       

        hitTestList.Reverse();

        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;

        hitTestList.Add(result.VisualHit);
        return HitTestResultBehavior.Continue;
    }

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