【问题标题】:How to get Active TextBox Windows Forms [duplicate]如何获取 Active TextBox Windows 窗体 [重复]
【发布时间】:2016-10-30 22:22:00
【问题描述】:

我有 2 个文本框,格式为 textbox1 和 textbox2(是的,很懒惰) 以及为应用程序创建类似复制和粘贴功能的任务 (出于实践原因)

但我不知道程序将如何确定哪个文本框是当前活动的文本框

    public partial class Form1 : Form
    {

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.F1) //Copy
        {

        }
        else if (e.KeyCode == Keys.F2) //Paste
        {

        }
    }
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    您的问题可能已经得到了答案。

    Form.ActiveControl 可能是你想要的。

    【讨论】:

      【解决方案2】:

      您可以使用ContainsFocus 属性确定激活了哪个TextBox

      private void Form1_KeyDown(object sender, KeyEventArgs e)
      {
          TextBox activeTextBox = textBox1.ContainsFocus 
                          ? textBox1
                          : (textBox2.ContainsFocus ? textBox2 : null);     
      
          if (e.KeyCode == Keys.F1) //Copy
          {
      
          }
          else if (e.KeyCode == Keys.F2) //Paste
          {
      
          }
      }
      

      或者Form.ActiveControl属性:

      private void Form1_KeyDown(object sender, KeyEventArgs e)
      {
          TextBox activeTextBox = ActiveControl as TextBox;
      
          if (e.KeyCode == Keys.F1) //Copy
          {
      
          }
          else if (e.KeyCode == Keys.F2) //Paste
          {
      
          }
      }
      

      【讨论】:

        【解决方案3】:

        您必须将发件人转换为TextBox 并获取其名称或任何标识您的文本框的内容。 负责任地做,使用 as : var textBox = sender as TextBox 然后检查它是否为空

        编辑:事件处理程序必须分配给TextBoxelements 而不是表单

        【讨论】:

        • 我必须为我的每个文本框都这样做吗?...
        • 这只有在 KeyDown 处理程序分配给 TextBoxes' KeyDown 事件时才有效。从它的名字我认为它被分配给Form的事件,所以sender总是Form,而不是TextBox
        • @kennedydelrosario 是的,您必须将此事件分配给每个TextBox
        猜你喜欢
        • 2010-10-20
        • 1970-01-01
        • 2010-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        相关资源
        最近更新 更多