在 WinForms 应用程序中找到焦点控件的首选方法是什么? [英] What is the preferred way to find focused control in WinForms app?

查看:20
本文介绍了在 WinForms 应用程序中找到焦点控件的首选方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the preferred/easiest way to find the control that is currently receiving user (keyboard) input in WinForms?

到目前为止,我想出了以下几点:

So far I have come up with the following:

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

从表单中,这可以简单地调用为(在 .NET 3.5+ 中,这甚至可以定义为表单上的扩展方法)-

From a form, this can be called simply as (in .NET 3.5+ this could even be defined as an extension method on the form) -

var focused = FindFocusedControl(this);

这样合适吗?

是否有我应该使用的内置方法?

Is there a built-in method that I should be using instead?

请注意,使用层次结构时,仅调用 ActiveControl 是不够的.想象一下:

Note that a single call to ActiveControl is not enough when hierarchies are used. Imagine:

Form
    TableLayoutPanel
        FlowLayoutPanel
            TextBox (focused)

(formInstance).ActiveControl 将返回对 TableLayoutPanel 的引用,而不是 TextBox(因为 ActiveControl 似乎只返回控件树中的直接活动子项,而我正在寻找叶控件).

(formInstance).ActiveControl will return reference to TableLayoutPanel, not the TextBox (because ActiveControl seems to only be returning immediate active child in the control tree, while I'm looking for the leaf control).

推荐答案

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

If you have other calls to the Windows API already, there's no harm in using Peters solution. But I understand your worries about it and would tend to a similar solution as yours, using only the Framework functionalities. After all, the performance difference (if there is one) shouldn't be significant.

我会采用非递归方法:

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

这篇关于在 WinForms 应用程序中找到焦点控件的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆