我需要在另一个控件的事件中找到鼠标下的控件。我可以从GetTopLevel
开始并使用GetChildAtPoint
进行迭代,但有更快的方法吗?
答案 0 :(得分:16)
这段代码没有多大意义,但它确实避免遍历Controls集合:
[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;
}
答案 1 :(得分:2)
未经测试且脱离我的头顶(也许很慢......):
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();
但是,我不确定这会有多可靠。