2

用于检测在 Windows 窗体中激活了哪些控件

this.ActiveControl = NameOfControl;

如何检测控件类型,例如活动控件是按钮还是文本框?

新编辑:

如果活动控件是文本框类型,我想在按键上做一些事情,否则什么也不做

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (this.ActiveControl == xxxx)
            {
                //do SomeThing
            }
              return base.ProcessCmdKey(ref msg, keyData);
        }

在 xxx 中,我应该输入控件的名称,但是对于文本框类型的所有控件,我该怎么做?

4

3 回答 3

3

要确定活动控件是按钮还是文本框,您可以使用is运算符。is 运算符检查对象是否与给定类型兼容。如果Control与 a 兼容Button并且表达式为真,则 Control一个按钮。

if (ActiveControl is Button)
{

}
else if (ActiveControl is TextBox)
{

}
于 2013-07-02T07:22:21.947 回答
1

您可以遍历 Form 上的所有控件并为 GotFocus 事件设置事件处理程序。在此事件处理程序中,您将设置变量:

    Control ActiveControl = null;

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (Control c in this.Controls)
        {
           if(c is TextBox)
           {
            c.GotFocus += (s, o) =>
                {
                    this.ActiveControl = s as Control;
                };
           }
        }
    }

当您使用带有“is”运算符的类型的 ActiveControl 对象测试时。

于 2013-07-02T07:25:48.053 回答
1

使用.GetType(),例如 this.ActiveControl.GetType() == typeof(Button)

于 2013-07-02T07:23:35.873 回答