在窗体中找到焦点控件(在.netCF中)

问题描述:

我有一个窗体,我想知道哪个控件具有焦点。在窗体中找到焦点控件(在.netCF中)

我该怎么做?我见过的最佳解决方案是让我重复屏幕上的所有控件。虽然可行,但仅仅知道哪个控件具有重点,似乎有很多工作要做。

它看起来像THIS是继续前进的CF.

你既可以做什么,也可以实现你自己的表单基类来为你处理任务。

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; 

} 

这是不可能避免控制迭代,但是如果这样的迭代将只发生一次,而不是每次都做到了,你想知道主动控制。然后,您可以只需调用ACTIVECONTROL按标准WinForms应用程序如下:

Control active = this.ActiveControl; 

这个唯一的缺点是,如果你不得不在运行时添加新的控制的需求,那么你就必须确保它们正确连接到control_GotFocus事件。

+0

虽然看起来不错,但这不起作用。这是因为LostFocus事件出现在下一个控件的GotFocus之前。因此,在LostFocus事件中,您无法知道焦点在哪里(使用此方法。但是,此方法工作正常:http://*.com/questions/1648596/c-net-compact-framework-custom-usercontrol-focus -issue/1648653#1648653) – Vaccano 2010-05-24 20:55:49

+0

这有点苛刻。它工作正常,而不是来自LostFocus事件。无论如何,我想不出一个情景,你可能想知道下一个关于LostFocus事件的重点控制。 – GenericTypeTea 2010-05-25 07:20:53

+0

我并不是故意要苛刻。抱歉。我非常感谢这个回应以及你投入的时间。至于为什么我想知道下一个控制...我觉得我有一个很好的理由。感谢你付出的努力。 (作为一个补充的感谢,我给了你一些更好的问题和答案upvotes。) – Vaccano 2010-05-25 15:02:34