naouf
naouf

Reputation: 637

How to know the last clicked textbox in C#?

This is not duplicated question there was a similar question asked here but its answers did not help me.

I have one button and 3 textBoxes on form1 (windows forms), the shown code achieves the following:

by clicking on the button it types its text into the last clicked textbox and it works perfect because all the 3 boxes are textbox type. Now I want to add a richTextBox in form1 and I want this richTextBox behaves same way as the 3 textboxs (I mean when I click on the richTextBox I still can type the text). In this case I have a mixed controls ( textBoxes and a richTextBox) if it was only richTextBoxes or only textBoxes then it is easy to solve.

I need to modify this code so one of the controls (3 textBoxes and richTextBox) gets focused if it was clicked and then button1 knows which box is clicked so it can insert the text in it.Can Anyone help me with this please.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public TextBox Selected_TextBox = null ;

    private void Form1_Load(object sender, EventArgs e)
    {
        this.ActiveControl = textBox1;
        textBox1.Focus();   // set textbox1 foucsed when form1 loads
        Selected_TextBox = textBox1;  // idintify the SelectedTextBox.
    }

    private void textBox1_Click(object sender, EventArgs e)
    {
        Selected_TextBox = sender as TextBox; // bcomes the selected one in click event
    }

    private void textBox2_Click(object sender, EventArgs e) 
    {
        Selected_TextBox = sender as TextBox; 
    }

    private void textBox3_Click(object sender, EventArgs e) 
    {
        Selected_TextBox = sender as TextBox;         
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Selected_TextBox.Focus(); 
        Selected_TextBox.SelectedText = button1.Text;
        Selected_TextBox.SelectionStart = Selected_TextBox.Text.Length;
    }
}

Upvotes: 0

Views: 184

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190925

Use TextBoxBase which is a common base class between TextBox and RichTextBox.

Upvotes: 6

Related Questions