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?
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With