0

I have a panel in a winforms application and I'm wondering if it is possible to see if there is UserControl at a coordinate, for example x:200, y:200.

I don't just want to detect UserControls with their top-left at x:200, y:200 but also to detect a UserControl if say, it was at x:150, y:150 with W:100, H:100.

I've given it a quick google but I can't find anything.

[edit] To sum up:

In the Black Panel I would like to be able to detect if there is a UserControl (shown in Red) at the Blue coordinate as shown in image 2 not just image 1.

enter image description here Image 2

Toby Smith
  • 1,505
  • 2
  • 15
  • 24
  • 2
    I don't understand your question. If you have a specific point that you want to know if it is contained by the boundary of the `UserControl`, why can't you just call the [`Rectangle.Contains(Point)`](https://msdn.microsoft.com/en-us/library/22t27w02(v=vs.110).aspx) method? What _specifically_ is it that you are having trouble figuring out here? Please provide [a good, _minimal_, _complete_ code example](https://stackoverflow.com/help/mcve) that shows clearly what you've tried so far, along with a detailed explanation of what's not working for you. – Peter Duniho Sep 24 '15 at 02:39
  • @PeterDuniho I have tried to make things clearer. I can't show what I've tried so far as I have been unable to find anything on this topic. – Toby Smith Sep 24 '15 at 03:31

2 Answers2

2

Step 1: Iterate over all windows (or controls) for those currently with Visible == true: How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

Step 2: For each Control, use the c.ClientRectangle property to get its bounding box relative to its parent.

Step 3: Translate the bounding box to screen coordinates using the c.RectangleToScreen(...) method.

Step 4: Test if the mouse is inside the Rectangle using the r.Contains(Point pt) method.

Community
  • 1
  • 1
Loathing
  • 5,109
  • 3
  • 24
  • 35
2

You can use Control.GetChildAtPoint Method (Point) for that, like this:

Control parent = your_panel;
Point pt = your_point;
// Uncomment if your point is in screen coordinates
// pt = parent.PointToClient(pt);
Control child = parent.GetChildAtPoint(pt);
if (child != null)
{
    // There is some control, but it might not be the one you are searching for.

    // Uncomment if you are searching for a direct child of your panel
    // while (child.Parent != parent) child = child.Parent;

    // Use other criterias. For instance:
    var userControl = child as UserControl;
    if (userControl != null)
    {
        // There you go.
    }
}
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343