有没有一种快速的方法来获得鼠标下的控制?

Sim*_*mon 12 .net c# winforms

我需要在另一个控件的事件中找到鼠标下的控件.我可以从使用开始GetTopLevel并迭代GetChildAtPoint,但有更快的方法吗?

Han*_*ant 17

这段代码没有多大意义,但它确实避免遍历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;
}
Run Code Online (Sandbox Code Playgroud)