如何使用按钮单击在特定文本框中输入文本
本文关键字:文本 输入 何使用 按钮 单击 | 更新日期: 2023-09-27 18:16:53
我正在开发一个WinForms应用程序。我的表单中有四个文本框和一个按钮。我在一个按钮上使用textBox1.SelectedText += "any string"
,因此它写入第一个TextBox
。如果我添加textBox1.SelectedText += "any string."
,那么它将同时写入textbox1和textbox2。
当我单击textbox1并按下按钮时,sting只在第一个文本框中写入,我单击第二个文本框并按下按钮,然后它写入第二个文本框。是否有任何方法可以做到这一点?
我使用下面的代码:
private void button1_Click(object sender, EventArgs e)
{
textBox1.SelectedText += "abc";
textBox2.SelectedText += "abc";
}
当我聚焦在控件上时,当我们按下按钮时,焦点转向按钮。那么,在按下按钮后,我们如何将焦点放在表单的其中一个文本框上呢?
你可以试试这个
TextBox selTB = null;
public Form1()
{
InitializeComponent();
textBox1.Enter += tb_Enter;
textBox2.Enter += tb_Enter;
textBox3.Enter += tb_Enter;
textBox4.Enter += tb_Enter;
}
~Form1()
{
textBox1.Enter -= tb_Enter;
textBox2.Enter -= tb_Enter;
textBox3.Enter -= tb_Enter;
textBox4.Enter -= tb_Enter;
}
private void tb_Enter(object sender, EventArgs e)
{
selTB = (TextBox)sender;
}
private void button1_Click(object sender, EventArgs e)
{
// Do what you need
selTB.SelectedText += "abc";
// Focus last selected textbox
if (selTB != null) selTB.Focus();
}
这个想法是,当你输入一个文本框,你存储它在selTB
。
当你点击按钮时,你知道哪个文本框是最后被选中的
您可以按如下样例,希望能给您一些启发。
public partial class Form7 : Form
{
private TextBox textBox = null;
public Form7()
{
InitializeComponent();
// Binding to custom event process function GetF.
this.textBox1.GotFocus += new EventHandler(GetF);
this.textBox2.GotFocus += new EventHandler(GetF);
}
private void GetF(object sender, EventArgs e)
{
// Keeps you selecting textbox object reference.
textBox = sender as TextBox;
}
private void button1_Click(object sender, EventArgs e)
{
// Changes you text box text.
if (textbox != null) textBox.SelectedText += "You text";
}
}