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

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

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

btn1 的文字必须粘贴到当前处于焦点的任何文本框中。

事件中,我的 btn1.OnClick

txt1.text = btn1.text;

当我把焦点转移到 txt2我怎么能把 btn1txt2.text 也是?所以当 btn1 的文本必须被粘贴到任何处于焦点的文本框中。

c# winforms button textbox
2个回答
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.coma342672113660130


1
投票
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.