繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM