设置在C#窗体中具有焦点的文本框值

本文关键字:焦点 文本 窗体 设置 | 更新日期: 2023-09-27 18:28:41

我有数字按钮,按下后会在不同的文本框中显示数字。现在我的问题是,我想检查哪个文本框有焦点,这样按下的数字就会输入到那个文本框中。我的代码:

private void btn_one_Click(object sender, EventArgs e)
{
    if (txt_one.Focused==true)
    {
        txt_one.Text += btn_one.Text;
    } 
    else if (txt_two.Focused==true)
    {
        txt_two.Text += btn_one.Text;
    }
}

现在我的问题是,上面的代码不起作用——哪里出了问题,解决方案是什么?我甚至用过类似的东西

private void btn_one_Click(object sender, EventArgs e)
{
    if (txt_one.Focus()==true)
    {
        txt_one.Text += btn_one.Text; 
    }
    else if (txt_two.Focus()=true)
    {
        txt_two.Text += btn_one.Text;
    }
}

在上述两种情况下,都会在两个文本框中输入文本。任何解决方案。

设置在C#窗体中具有焦点的文本框值

这个问题有点棘手(根据我处理Enter, Focus, LostFocus, Leave事件的经验,所有这些事情有时会让你头疼,如果可能的话,你应该避免处理它们),当你点击Button时,你可以知道的当前Focused控件正是ButtonActiveControl是访问它的一种短方法)。因此,解决方案是我们必须记录聚焦TextBox的轨迹,将其保存在参考中,并在需要时使用它。事实上,如果您的TextBoxes以外的控件被聚焦,我们必须将变量lastFocused重置为null:

TextBox lastFocused;
//Enter event handler for all your TextBoxes
private void TextBoxes_Enter(object sender, EventArgs e){
  lastFocused = sender as TextBox;
}
//Click event handler for your button
private void btn_one_Click(object sender, EventArgs e){
  if(lastFocused != null) lastFocused.Text += btn_one.Text;
}