如何在 C# 中更改焦点文本框的文本?

How to change the text of focused textbox in C#?

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

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

我的btn1.OnClick事件是

txt1.text = btn1.text;

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

当按钮的点击事件被触发时,按钮而不是文本框获得了焦点。因此,您需要捕获最后获得焦点的文本框并使用它。

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

    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 函数的功劳:

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;
    }
}