【问题标题】:Detect user controls inner controls focus检测用户控件内部控件焦点
【发布时间】:2011-12-12 05:28:51
【问题描述】:

是否可以检测控件是否已在用户控件中获得焦点?我的意思不是我们在设计时添加到用户控件中的某些控件,而是我们在表单上使用用户控件后添加的控件。一个典型的例子是面板。我的用户控件就像一个面板,我想检测我的用户控件上的包含(嵌套)控件何时获得任何焦点。

谢谢大家!

【问题讨论】:

    标签: c# .net user-controls


    【解决方案1】:

    我的方法是在创建 UserControl 并且您未处于设计模式时,循环浏览用户控件中的每个控件,将钩子添加到它们的 GotFocus 事件并将钩子指向 UserControl 的方法(比如 ChildControlGotFocus),这反过来引发用户控件的主机可以使用的事件。

    例如,下面是一个实现此功能的示例 UserControl:

    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
    
            if (!this.DesignMode)
            {
                RegisterControls(this.Controls);
            }
    
        }
        public event EventHandler ChildControlGotFocus;
    
        private void RegisterControls(ControlCollection cControls)
        {
            foreach (Control oControl in cControls)
            {
                oControl.GotFocus += new EventHandler(oControl_GotFocus);
                if (oControl.HasChildren)
                {
                    RegisterControls(oControl.Controls);
                }
            }
        }
    
        void oControl_GotFocus(object sender, EventArgs e)
        {
            if (ChildControlGotFocus != null)
            {
                ChildControlGotFocus(this, new EventArgs());
            }
        }
    }
    

    【讨论】:

    • 谢谢。我真的很感激你所做的这件事。
    猜你喜欢
    • 2011-08-24
    • 1970-01-01
    • 2010-12-29
    • 2014-02-20
    • 2010-11-12
    • 1970-01-01
    • 2012-11-12
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多