Leave (Lost Focus) firing twice why???

mutlyp

Member
Joined
Oct 11, 2012
Messages
8
Programming Experience
10+
I have a vb.net windows application. I have a textbox that has a 'Leave' method. Inside the 'Leave' method I have a textbox2.focus call so when the code gets to the end of the 'Leave' method the focus will then go to textbox2.

Heres the problem:
So the focus is on the textbox and I hit the Tab key, automatically the 'Leave' for the textbox fires and does all the code in the 'Leave' method. Then when it gets to the end of the code in the 'Leave' method it hits the textbox2.focus call. BUT right after textbox2.Focus call the code goes back to the begining of the 'Leave' method and runs all that code again. When it gets to the end of the code in the 'Leave' method and hits the textbox2.focus call again, this time it continues to the end of the method then after the 'End Sub' for the 'Leave' method it goes back to the textbox2.focus call from the first time through and then goes to the end of the method and that's it.

Why does the textbox2.focus call make the code go back to the begining of the 'Leave' method when hitting the 'Tab' key has already made the 'Leave' method fire?

What can I do to prevent the code from going through the code twice????

Thank you
 
When you explicitly call textbox2.focus, it will fire the Leave event on the previous control. You can find more information at Control.Leave Event (System.Windows.Forms). Also note the following cautionary note on the MSDN page which is what you are doing.

Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding. For more information, see the WM_KILLFOCUS topic in the "Keyboard Input Reference" section, and the "Message Deadlocks" section of the "About Messages and Message Queues" topic in the MSDN library at MSDN Library.

Hope this helps!
 
Back
Top