Exit Form on Lost Focus

I have a form with a text box.  If a user enters "END" I want to exit the program.  In the LostFocus event, I do exactly that.  If the user tabs off the field, everything works fine.  If the user clicks in another field, I get the following error:

"Cannot access a disposed object named 'TextBox'"

What am I doing wrong?
RySk8er30Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

EdMarshCommented:
Hi RySk8er30 - Not sure why you get that error - maybe somebody else can help with that, but instead of using the LostFocus event, try using Leave instead ...

   Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
        If TextBox1.Text = "END" Then Me.Close()
    End Sub

HTH

Ed.
EdMarshCommented:
Hmmm - maybe not - I've just re-created the error using Leave too - let me rethink ...

Ed
EdMarshCommented:
Ahhh - that's better. Looks like your app is closing down before all messages have been dealt with.

Try this ...

   Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus
        If TextBox1.Text = "END" Then Application.Exit()
    End Sub

This causes all message pumps to be cleared before the app closes. Seems to work fine for me.

Regards Ed

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.