在.NET CF中查找窗体中的焦点控件

3

我有一个表单,想知道哪个控件当前获得了焦点。

如何实现呢?目前最好的解决方案是遍历屏幕上的所有控件。虽然这种方法可行,但似乎为了只是知道哪个控件获得了焦点而做很多工作。

2个回答

4

看起来这个是在CF上解决问题的方法。


2

你可以按照thelost所说的做法,或者实现自己的表单基类来处理该任务。

public class BaseForm : Form
{
    public BaseForm() 
    {
        this.Load += new EventHandler(BaseForm_Load);
    }

    void BaseForm_Load(object sender, EventArgs e)
    {
        this.HandleFocusTracking(this.Controls);
    }

    private void HandleFocusTracking(ControlCollection controlCollection)
    {
        foreach (Control control in controlCollection)
        {
            control.GotFocus += new EventHandler(control_GotFocus);
            this.HandleFocusTracking(control.Controls);
        }
    }

    void control_GotFocus(object sender, EventArgs e)
    {
        _activeControl = sender as Control;
    }

    public virtual Control ActiveControl
    {
        get { return _activeControl; }
    }
    private Control _activeControl;

}

无法避免控制迭代,但如果您按照以下方式执行,则迭代仅会发生一次,而不是每次想要了解活动控件时都会发生。然后,您可以像标准的WinForms应用程序一样调用ActiveControl:

Control active = this.ActiveControl;

这样做的唯一缺点是,如果您需要在运行时添加新控件,则必须确保它们已正确连接到“control_GotFocus”事件。

虽然看起来很不错,但这并不起作用。这是因为LostFocus事件出现在下一个控件的GotFocus事件之前。因此,在LostFocus事件中,您无法知道焦点在哪里(使用此方法)。但是,此方法可以正常工作:http://stackoverflow.com/questions/1648596/c-net-compact-framework-custom-usercontrol-focus-issue/1648653#1648653。 - Vaccano
有点严厉。它可以正常工作,只是不能从LostFocus事件中工作。我无法想象在LostFocus事件中你会想知道下一个聚焦的控件的情况。 - djdd87
我并不是有意要表现得很苛刻。非常抱歉。我非常感激您的回复和付出的时间。至于为什么我想知道下一个控件...我觉得我有充分的理由。感谢您的努力。(作为额外的感谢,我给了一些赞成票给您更好的问题和答案。) - Vaccano
@Vaccano - 我并没有把它当成个人攻击。我所说的“严厉”是指说“这不起作用”暗示着它根本就不起作用。很高兴能帮忙。 - djdd87

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接