簡體   English   中英

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

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

如何將button.OnClick的文本粘貼到當前聚焦的 TextBox 中? 我的表單有一個按鈕btn1與文本"this is test"和兩個文本框, 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 function: https://stackoverflow.com/a/3426721/13660130

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM