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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/586479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:17:10  来源:igfitidea点击:

Is there a quick way to get the control that's under the mouse?

c#.netwinforms

提问by Simon

I need to find the control under the mouse, within an event of another control. I could start with GetTopLeveland iterate down using GetChildAtPoint, but is there a quicker way?

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

采纳答案by Hans Passant

This code doesn't make a lot of sense, but it does avoid traversing the Controls collections:

这段代码没有多大意义,但它确实避免了遍历 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;
}

回答by Lucas Jones

Untested and off the top of my head (and maybe slow...):

未经测试并且在我的头顶上(也许很慢......):

Control GetControlUnderMouse() {
    foreach ( Control c in this.Controls ) {
        if ( c.Bounds.Contains(this.PointToClient(MousePosition)) ) {
             return c;
         }
    }
}

Or to be fancy with LINQ:

或者喜欢 LINQ:

return Controls.Where(c => c.Bounds.Contains(PointToClient(MousePosition))).FirstOrDefault();

I'm not sure how reliable this would be, though.

不过,我不确定这有多可靠。