c# - 有没有快速的方法来获得鼠标下的控件?

标签 c# .net winforms

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

最佳答案

这段代码没有多大意义,但它确实避免了遍历控件集合:

[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;
}

关于c# - 有没有快速的方法来获得鼠标下的控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/586479/

相关文章:

c# - 我如何在 Monogame 项目中实现 Awesomium 1.7.4.2?

c# - AWS CDK : Vpc subnet conflicts with another subnet

c# - 使用 Interlocked.Exchange 更新引用和 Int32

c# - 无法使用 XDocument 查询 XML 文档并获得所需的结果

vb.net - 隐藏一个 VB.Net 后重新排列面板

c# - 避免手动编写类似代码的简单方法

c# - 如何通过命令行在 MSBuild 中指定 CodeAnalysisRuleset

c# - 将文本框值与其他控件中的值绑定(bind)

c# - Devexpress PopupMenu Closing 事件类似于 Windows Contextmenu Closing 事件

c# - SynchronizationContext.Current 在主 UI 线程的 Continuation 中为 null