How to get control under mouse cursor?

Have a look at GetChildAtPoint. You will have to do some extra work if the controls are contained in a container, see Control.PointToClient.


Maybe GetChildAtPoint and PointToClient is the first idea for most people. I also used it first. But, GetChildAtPoint doesn't work properly with invisible or overlapped controls. Here's a well-working code and it manages those situations.

using System.Drawing;
using System.Windows.Forms;

public static Control FindControlAtPoint(Control container, Point pos)
{
    Control child;
    foreach (Control c in container.Controls)
    {
        if (c.Visible && c.Bounds.Contains(pos))
        {
            child = FindControlAtPoint(c, new Point(pos.X - c.Left, pos.Y - c.Top));
            if (child == null) return c;
            else return child;
        }
    }
    return null;
}

public static Control FindControlAtCursor(Form form)
{
    Point pos = Cursor.Position;
    if (form.Bounds.Contains(pos))
        return FindControlAtPoint(form, form.PointToClient(pos));
    return null;
}

This will give you the control right under the cursor.

Tags:

C#

Winforms

Mouse