You can get the focused
TextBox
using
Control.Focused[
^] property. See
this[
^] example.
[UPDATE]
My guess is that you want to append text to the
TextBox
that is focused. You could write your own helper method say
void AppendText(string strToAppend)
that checks for the active TextBox and append the given string to it.
For example if you have 2
TextBoxes
(textBox1 and textBox2) than you could write get focused
TexBox
method like this:
private TextBox GetFocusedTextBox()
{
if (textBox1.Focused == true)
{
return textBox1;
}
if (textBox2.Focused == true)
{
return textBox2;
}
return null;
}
If you have lots of textboxes then you can change the
GetFocusedTextBox()
method to iterate through the controls on the form using the first example from the link that I gave you.
Your append text method could be something like:
private void AppendText(string strToAppend)
{
TextBox tbFocused = GetFocusedTextBox();
if(tbFocused != null)
{
tbFocused.Text += strToAppend;
}
else
{
}
}
This is an easy solution and you can call the
AppendText
method where you want to append text to the focused
TextBox
. I hope this helps. Feel free to post a comment in case this not enough or not clear. :)
[/UPDATE]
[UPDATE 2.1]
Sorry for late answer, my internet connection was down but I'm here with a working example for you. :)
First I will paste the code and after that will try to explain:
public partial class Form1 : Form
{
private TextBox tbSelected;
private int posCaret;
private int selLength;
public Form1()
{
InitializeComponent();
textBox1.Leave += new System.EventHandler(textBox_Leave);
textBox2.Leave += new System.EventHandler(textBox_Leave);
textBox1.Select();
tbSelected = textBox1;
posCaret = 0;
selLength = 0;
}
private void button1_Click(object sender, EventArgs e)
{
RestoreLastSelection();
tbSelected.SelectedText = "S";
}
private void button2_Click(object sender, EventArgs e)
{
RestoreLastSelection();
tbSelected.SelectedText = "FOO";
}
private void textBox_Leave(object sender, EventArgs e)
{
tbSelected = (TextBox)sender;
posCaret = tbSelected.SelectionStart;
selLength = tbSelected.SelectionLength;
}
private void RestoreLastSelection()
{
tbSelected.Select();
posCaret = tbSelected.SelectionStart;
selLength = tbSelected.SelectionLength;
}
}
I've created a new project (Windows forms application) added 2 buttons and 2 textboxes. My approach is very simple. Have a look at the
Control.Leave[
^] event. I use this event to register the last focused textbox, caret position in it and the length of the selected text. After a button click occurs I restore the selection in the textbox and then replace the selected text. This way you can add text to cursor position and/or replace selected text. Examine the source above. I believe that this approach is easy to understand and use. Give it a try and let me know if there are some problems. :)
[/UPDATE 2.1]