我需要找到鼠标下的控制,另一个控件的事件中。我可以先参观一下 GetTopLevel
和重复使用上下 GetChildAtPoint
,但有一个更快的方法?
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?
这code没有做出很大的意义,但它确实避免遍历控件集合:
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;
}