tags:

views:

74

answers:

1

I have two textboxes, and a button. When I press the button, I want to know where my current caret is (either of the two boxes). I need this to know where to insert a certain text. I tried textbox1.Focused; textbox1.enabled but neither worked. How should I implement this? Thanks

+1  A: 

Keep in mind that when you click the button, your textboxes will no longer have focus. You'll want a method of keeping track of what was in focus before the button's click event.

Try something like this

public partial class Form1 : Form
{
    private TextBox focusedTextbox = null;

    public Form1()
    {
        InitializeComponent();
        foreach (TextBox tb in this.Controls.OfType<TextBox>())
        {
            tb.Enter += textBox_Enter;
        }
    }

    void textBox_Enter(object sender, EventArgs e)
    {
        focusedTextbox = (TextBox)sender;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (focusedTextbox != null)
        {
            // put something in textbox
            focusedTextbox.Text = DateTime.Now.ToString();
        }
    }
}
Anthony Pegram
Thanks! I have to Textbox.GotFocus instead of Textbox.Enter
chown