Get currently textbox in C #

I have two text fields and a button. When I press the button, I want to know where my current carriage is located (one of two boxes). I need this to know where to insert certain text. I have tried textbox1.Focused; textbox1.enabledbut it didnโ€™t work. How do I implement this? Thanks

+3
source share
2 answers

Keep in mind that when you click the button, your text fields will no longer have focus. You will need a method for tracking what was in focus before the button 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();
        }
    }
}
+13
source

. , .

, , textbox1_GotFocus(), textbox2_GotFocus(). , textbox GotFocus(), . , , , , .

, , .

+1

Source: https://habr.com/ru/post/1747722/


All Articles