查找当前正在WinForms中接收用户(键盘)输入的控件的首选/最简单方法是什么?

到目前为止,我已经得出以下结论:

public static Control FindFocusedControl(Control control)
{
    var container = control as ContainerControl;
    return (null != container
        ? FindFocusedControl(container.ActiveControl)
        : control);
}

在表单中,这可以简单地称为(在.NET3.5+中,这甚至可以定义为表单上的扩展方法)-

var focused = FindFocusedControl(this);

这样合适吗?

有没有我应该改用的内置方法?

请注意,使用层次 struct 时,对ActiveControl的单个调用是不够的.想象一下:

Form
    TableLayoutPanel
        FlowLayoutPanel
            TextBox (focused)

(formInstance).ActiveControl将返回对TableLayoutPanel的引用,而不是文本框(因为在我寻找叶控件时,ActiveControl似乎只返回控件树中的立即活动子控件).

推荐答案

如果您已经有其他对Windows API的调用,那么使用Peters解决方案没有什么坏处.但我理解您对此的担忧,并倾向于采用与您的解决方案类似的解决方案,只使用框架功能.毕竟,性能差异(如果有)应该不会很大.

我将采用非递归方法:

public static Control FindFocusedControl(Control control)
{
    var container = control as IContainerControl;
    while (container != null)
    {
        control = container.ActiveControl;
        container = control as IContainerControl;
    }
    return control;
}

.net相关问答推荐

如何使用.NET8MapIdentityApi设置OpenApi操作ID

在 .NET 7 项目上设置 Sentry 时遇到问题

查询 MongoDb 中嵌入式文档中的一个字段,该字段抛出调用运算符的左侧必须是对持久属性的直接访问

process.WaitForExit() 异步

log4net 与 TraceSource

我可以从 .NET/C# 获取其他进程的命令行参数吗?

使用 EPPlus 时如何设置列类型

找不到 Microsoft.Office.Interop Visual Studio

如何根据新的安全策略在 .Net 中发送邮箱?

Microsoft.Practices.ServiceLocation 来自哪里?

C# 相当于 Java 的 <?在泛型中扩展 Base>

System.String.Copy 在 .NET 中有什么用?

为什么 System.Timers.Timer 能在 GC 中存活,而 System.Threading.Timer 不能?

返回 IList 是否比返回 T[] 或 List 更糟糕?

如何禁用 Alt + F4 关闭表单?

ToLowerInvariant() 有什么问题?

静态方法继承的正确替代方法是什么?

从 C# 中的字符串中删除最后一个字符.优雅的方式?

.NET 委托类型的正确命名约定?

如何获取当前的 ProcessID?