C # Get control at a specific position in the form

This is the inverse question of C # Get a control position in the form .

Given the location of the point in the form, how can I find out which control is displayed to the user in this position?

I am currently using an event of the HelpRequested form to show a separate help form, as shown in MSDN: MessageBox.Show Method .

In the MSDN example, a control is used to define the help message sender, but senderit is always a form, not a control in my case.

I would like to use HelpEventArgs.MousePos to get a specific control on the form.

+3
source share
3 answers

You can use the Control.GetChildAtPoint method in the form. You may need to do this recursively if you need to go through several levels. See this answer .

+4
source

You can use Control.GetChildAtPoint :

var controlAtPoint = theForm.GetChildAtPoint(thePosition);
+2
source

This is retrieving the modified code using both Control.GetChildAtPoint and Control.PointToClient to recursively search for the control with the tag defined at the point that the user clicked.

private void Form1_HelpRequested(object sender, HelpEventArgs hlpevent)
{
    // Existing example code goes here.

    // Use the sender parameter to identify the context of the Help request.
    // The parameter must be cast to the Control type to get the Tag property.
    Control senderControl = sender as Control;

    //Recursively search below the sender control for the first control with a Tag defined to use as the help message.
    Control controlWithTag = senderControl;
    do
    {
        Point clientPoint = controlWithTag.PointToClient(hlpevent.MousePos);
        controlWithTag = controlWithTag.GetChildAtPoint(clientPoint);

    } while (controlWithTag != null && string.IsNullOrEmpty(controlWithTag.Tag as string));

    // Existing example code goes here.    
}
0
source

Source: https://habr.com/ru/post/1787333/


All Articles