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

问题描述 投票:0回答:2

如何将按钮的文本粘贴到当前聚焦的文本框中?

我的表单有一个带有文本“ this is test”的按钮btn1和两个文本框txt1和txt2。

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

我的btn1.OnClick事件为

txt1.text = btn1.text;

当我将焦点更改为txt2时,如何将btn1的文本也粘贴到txt2.text上?

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

c# winforms button textbox
2个回答
0
投票

一个粗略而快速的实现,只要您所有的文本框都在加载表单上,它就应该起作用。处理不是形式的直接子元素的嵌套文本框。

    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


0
投票
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.