首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用按钮单击在特定文本框中输入文本

如何使用按钮单击在特定文本框中输入文本
EN

Stack Overflow用户
提问于 2011-12-03 19:49:48
回答 2查看 9K关注 0票数 2

我正在开发一个WinForms应用程序。我的表单中有四个文本框和一个按钮。我在单击按钮时使用textBox1.SelectedText += "any string",这样它就会写入第一个TextBox。如果我添加textBox1.SelectedText += "any string.",那么它会同时写入textbox1和textbox 2。

当我点击textbox1,然后按下按钮,然后刺只写在第一个文本框中,我点击第二个文本框,按下按钮,然后它写入第二个文本框.Is,有什么方法可以这样做吗?

我使用了下面的代码。

代码语言:javascript
运行
复制
private void button1_Click(object sender, EventArgs e)
{
    textBox1.SelectedText += "abc";
    textBox2.SelectedText += "abc";          
}

当我将焦点放在控件上时,当我们按下按钮时,焦点就转到按钮上。那么,在按下按钮之后,如何将焦点放在表单的一个文本框上呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-12-03 19:57:00

你可以试试这个

代码语言:javascript
运行
复制
    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中。

所以当你点击按钮时,你就知道哪个文本框是最后一个被选中的。

票数 2
EN

Stack Overflow用户

发布于 2011-12-03 20:24:47

你可以拿下面的样品,希望这能给你灵感。

代码语言:javascript
运行
复制
 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";
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8367435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档