Is there a quick way to get the control that's under the mouse?

I need to find the control under the mouse, within an event of another control. I could start with GetTopLevel and iterate down using GetChildAtPoint, but is there a quicker way?


Solution 1:

This code doesn't make a lot of sense, but it does avoid traversing the Controls collections:

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(Point pnt);

private void Form1_MouseMove(object sender, MouseEventArgs e) {
  IntPtr hWnd = WindowFromPoint(Control.MousePosition);
  if (hWnd != IntPtr.Zero) {
    Control ctl = Control.FromHandle(hWnd);
    if (ctl != null) label1.Text = ctl.Name;
  }
}

private void button1_Click(object sender, EventArgs e) {
  // Need to capture to see mouse move messages...
  this.Capture = true;
}

Solution 2:

Untested and off the top of my head (and maybe slow...):

Control GetControlUnderMouse() {
    foreach ( Control c in this.Controls ) {
        if ( c.Bounds.Contains(this.PointToClient(MousePosition)) ) {
             return c;
         }
    }
}

Or to be fancy with LINQ:

return Controls.Where(c => c.Bounds.Contains(PointToClient(MousePosition))).FirstOrDefault();

I'm not sure how reliable this would be, though.