How to get the DependencyObject under the mouse cursor

No.of Views1575
Bookmarked0 times
Downloads 
Votes0
By  Prabu   On  23 Jun 2010 10:06:38
Tag : WPF , Miscellaneous
How to get the DependencyObject under the mouse cursor
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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 Panelprivate 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;
    }

 I hope this is help to you all.thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
Prabu
Occupation-Software Engineer
Company-
Member Type-Fresh
Location-India
Joined date-23 Jun 2010
Home Page-
Blog Page-http://prabu-guru.blogspot.com/
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top