[英]Is there a quick way to get the control that's under the mouse?
我需要在另一个控件的事件中找到鼠标下的控件。 我可以从GetTopLevel
开始并使用GetChildAtPoint
向下迭代,但是有更快的方法吗?
这段代码没有多大意义,但它确实避免了遍历控件 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;
}
未经测试并且在我脑海中浮现(也许很慢......):
Control GetControlUnderMouse() {
foreach ( Control c in this.Controls ) {
if ( c.Bounds.Contains(this.PointToClient(MousePosition)) ) {
return c;
}
}
}
或者看中 LINQ:
return Controls.Where(c => c.Bounds.Contains(PointToClient(MousePosition))).FirstOrDefault();
不过,我不确定这有多可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.