0

I wanted to focus to a TextBox when I leave an other TextBox. Let's say I have 3 textboxes. The focus is in the first one, and when I click into the second one, I want to put the focus into the last one instead. I subscribed to the first textbox's Leave event and tried to focus to the third textbox like: third.Focus(). It gains focus for a moment but then the second one got it eventually (the one I clicked). Strangely if I replace the second TextBox to a MaskedTextBox (or to any other control), the focus remains on the third one. Pressing Tab does work though.

These are plain textboxes right from the toolbox.

What is the reason, how can I solve this?

user3567816
  • 106
  • 1
  • 1
  • 8

1 Answers1

1

Try to handle Enter event of the textBox2. (In properties window double click on Enter event)

//From Form1.Designer.cs

this.textBox2.Enter += new System.EventHandler(this.textBox2_Enter);
private void textBox2_Enter(object sender, EventArgs e)
{
   textBox3.Focus();
}

EDIT:

This code looks very strange, but it works for me. According to this post HERE I use ActiveControl property instead of Focus() method. But behavior of TextBox is very strange because it try to be focused multiple times.

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

            foreach (Control control in Controls)
            {
                control.LostFocus += (s, e) => Console.WriteLine(control.Name + " LostFocus");
                control.GotFocus += (s, e) =>
                {
                    Console.WriteLine(control.Name + " GotFocus");
                    if (!requestedFocusToTextBox2) return;
                    ActiveControl = textBox2; //textBox2.Focus() doesn't work
                    requestedFocusToTextBox2 = false;
                };
            }
        }

        private bool requestedFocusToTextBox2;

        private void textBox1_Leave(object sender, EventArgs e)
        {
            ActiveControl = textBox2;
            requestedFocusToTextBox2 = true;
        }
    }
Michael Navara
  • 1,111
  • 2
  • 8
  • 13
  • The second textbox should remain editable / clickable so always throwing back the focus is not an option. – user3567816 Aug 05 '21 at 09:06
  • I don't understand your requested behavior. Can you use ```TabOrder``` and ```TabStop``` properties? Is it possible to implement some condition to ```Enter``` event? – Michael Navara Aug 05 '21 at 09:18
  • When I leave a particular textbox anyhow (clicking to a button or whatever), an other particular textbox should be focused, Leaving another textbox shouldn't activate the focusing. – user3567816 Aug 05 '21 at 09:43
  • I edited my post with another example. This works form me, but I don't know if it is the best way – Michael Navara Aug 05 '21 at 13:05