textboxvb6lostfocusdefaultbutton

Textbox lostfocus event doesn't fire when using a default button


Today I stumbled upon a problem with a LostFocus event from a TextBox that didn't fire. Most clients didn't have any problems but a small portion of them reported unexpected behavior. After some research I found that the clients who didn't had the problem clicked on the "Ok" button with the mouse while the other clients pressed Enter on their keyboard. The "Ok" button was the default button on the Form so pressing Enter should work just fine. The problem is that pressing Enter doesn't fire a LostFocus event on the TextBox with focus.

After some Googling it was pretty clear that this is the expected behavior of a default button. The focus never loses the TextBox and the code behind the CommandButton Click event is being run without it being clicked.

How to get the LostFocus event to fire when using a default button?


Solution

  • A simple hack that worked for me is to set the focus to the "Ok" button whenever the Click event is being fired. That way the current control automatically runs its LostFocus event. Don't forget to put an extra DoEvents after setting the focus. Otherwise the LostFocus event fire after your other code has been executed.

    Private Sub cmdOk_Click()
        cmdOK.SetFocus
        DoEvents
        'Run your other code
    End Sub