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?
-
Why do you need to start at GetTopLevel, couldn't you simply go to GetChildAtPoint directly?– Marcus LFeb 25, 2009 at 15:35
-
(a) The control under the mouse isn't necessarily a child of the control whose event is firing, and (b) I would still have to iterate down to find the innermost control.– SimonFeb 25, 2009 at 15:36
Add a comment
|
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;
}
-
Makes perfect sense to me. :-) WindowFromPoint grabs the window handle directly under the mouses position on the screen, regardless of containment. Control.FromHandle translates it into a .Net control (if possible). Boom, done. Very slick.– Jason DMar 11, 2010 at 14:25
-
-
-
POINT pt; HWND hwnd; GetCursorPos (&pt); //find the control or window that lies underneath the mouse cursor. hwnd= WindowFromPoint (pt);– MathArtOct 27, 2021 at 7:03
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.
-
I just used this, it's great to get every control under a mouse position. However, it should be c.Bounds.Contains(Point p) not c.Bounds.IntersectsWith(Rectangle r).– snickerOct 19, 2009 at 22:54
-
MousePosition
will return a newpoint
at each call which is not good for performance, it is better to cache that or betterPointToClient(MousePosition)
into a variable in your loop Sep 25, 2018 at 10:02