【问题标题】:How to change the text of focused textbox in C#?如何在 C# 中更改焦点文本框的文本?
【发布时间】:2020-09-26 07:58:35
【问题描述】:

如何将button.OnClick 的文本粘贴到当前聚焦的TextBox 中?我的表单有一个按钮btn1 和文本"this is test" 和两个文本框txt1txt2

单击btn1 时,必须将其文本粘贴到当前焦点所在的任何文本框。

btn1.OnClick的事件是

txt1.text = btn1.text;

当我将焦点更改为txt2 时,如何将btn1 的文本也粘贴到txt2.text?因此,当单击btn1 时,必须将其文本粘贴到任何焦点所在的文本框。

【问题讨论】:

  • 应该是txt2.text = txt1.text;
  • @viveknuna,我知道,但我如何在运行时做到这一点?我的意思是当点击 btn1 时,任何文本框的值都必须改变。
  • 必须改成什么?
  • 到 btn1 的文本。 btn1 的文本是 "test" ,所以当 btn1 被点击时,无论哪个文本框处于焦点,它的文本也会是 "test" ,希望它现在清楚
  • 你可以这样做if (txt1.Focused){ btn1.text = txt1.text; } else if(txt2.Focused) {btn1.text = txt2.text;}

标签: c# winforms button textbox


【解决方案1】:

当按钮的点击事件被触发时,按钮现在拥有焦点而不是文本框。因此,您需要捕获最后一个具有焦点的文本框并使用它。

这是一个粗略而快速的实现,只要您的所有文本框都在加载的表单上,它就应该可以工作。它甚至适用于不是表单直接子级的文本框(例如,包含在面板或标签页中):

    public IEnumerable<Control> GetAll(Control control, Type type)
    {
        var controls = control.Controls.Cast<Control>();

        return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                  .Concat(controls)
                                  .Where(c => c.GetType() == type);
    }

    private TextBox lastFocussedTextbox;

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach(TextBox textbox in GetAll(this, typeof(TextBox)))
        {
            textbox.LostFocus += (_s, _e) => lastFocussedTextbox = textbox;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if(lastFocussedTextbox != null)
        {
            lastFocussedTextbox.Text = button1.Text;
        }
    }

GetAll 函数的功劳:https://stackoverflow.com/a/3426721/13660130

【讨论】:

    【解决方案2】:
    Declare global variable
    
    private Control _focusedControl;
    
    Attach below event to all your textboxes.
    private void TextBox_GotFocus(object sender, EventArgs e)
    {
        _focusedControl = (Control)sender;
    }
    Then in your button click event.
    private void btn1_Click(object sender, EventArgs e)
    {
        if (_focusedControl != null)
        {
        //Change the color of the previously-focused textbox
            _focusedControl.Text = btn1.Text;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多