Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

winforms

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?

like image 495
Simon Avatar asked Feb 25 '09 15:02

Simon


2 Answers

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;
}
like image 153
Hans Passant Avatar answered Sep 28 '22 18:09

Hans Passant


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.

like image 26
Lucas Jones Avatar answered Sep 28 '22 16:09

Lucas Jones