Logo

Hacker’s Guide to Visual FoxPro
An irreverent look at how Visual FoxPro really works. Tells you the inside scoop on every command, function, property, event and method of Visual FoxPro.

GotFocus, LostFocus

These events fire when an object gains or loses focus. They’re similar to the When and Valid events, but don’t include any testing to see whether the object can get or lose the focus. Also, unlike Valid, LostFocus fires every time focus leaves the control, whether or not the user has actually used the control.

Usage

PROCEDURE oObject.GotFocus | oObject.LostFocus
[ LPARAMETERS nIndex ]

The nIndex parameter is needed only if the method is for a control array.

GotFocus fires after When for the same object, and only if When returns .T. In other words, only if the object is actually allowed to have the focus.

LostFocus fires when you leave the object. For objects where Valid fires as you leave (text boxes and edit boxes, for example), Valid fires first. If Valid returns .T., allowing focus to leave, LostFocus fires. LostFocus is really useful, though, in controls that don’t always fire Valid. You can still detect that the user is moving along and act accordingly. This ability was sorely lacking in FoxPro 2.x.

In the first edition of this book, we recommended against using the SetFocus method in either of these methods. At the time, we said that the results were odd and unpredictable, though we couldn’t make anything disastrous happen. Since then, Microsoft has declared that you can’t use SetFocus in the Valid method, meaning that LostFocus is really your only chance to decide where focus lands at runtime. We’ve heard a few stories about odd behavior and seen some mildly strange firing sequences with SetFocus in LostFocus, but we still haven’t come across anything disastrous and haven’t personally seen any behavior that gives us pause. So, at this point, we will cautiously retract the original warning, leaving it with just a “If you see something strange, check out interactions between LostFocus and SetFocus.”

Example

* You might enable/disable certain options only when you're
* sitting on a particular control. In this case, we enable
* a button as we go in and disable it on the way out.
PROCEDURE edtDetails.GotFocus
* Enable the button to show more details
ThisForm.cmdBlowItUp.Enabled = .T.
ENDPROC

PROCEDURE edtDetails.LostFocus
* Disable the details button
ThisForm.cmdBlowItUp.Enabled = .F.
ENDPROC

See Also

Activate, Deactivate, SetFocus, When, Valid