是否有一个快速的方式来获得控制这下鼠标?鼠标、这下、有一个、快速

2023-09-02 21:30:59 作者:地球是个圆圆的球球

我需要找到鼠标下的控制,另一个控件的事件中。我可以先参观一下 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;
}
 
精彩推荐
图片推荐