Focus is the ability to receive user input through the mouse or keyboard. When an object has the focus, it can receive input from a user. In the Microsoft Windows interface, several applications can be running at any time, but only the application with the focus will have an active title bar and can receive user input. On a Visual Basic form with several text boxes, only the text box with the focus will display text entered by means of the keyboard.
The GotFocus and LostFocus events occur when an object receives or loses focus. Forms and most controls support these events.
Event | Description |
GotFocus | Occurs when an object receives focus. |
LostFocus | Occurs when an object loses focus. A LostFocus event procedure is primarily used for verification and validation updates, or for reversing or changing conditions you set up in the object's GotFocus procedure. |
You can give focus to an object by:
You can see when some objects have the focus. For example, when command buttons have the focus, they appear with a highlighted border around the caption (see Figure 3.19).
Figure 3.19 A command button showing focus
An object can receive focus only if its Enabled and Visible properties are set to True. The Enabled property allows the object to respond to user-generated events such as keyboard and mouse events. The Visible property determines whether an object is visible on the screen.
Note A form can receive focus only if it doesn't contain any controls that can receive the focus.
Controls also have a Validate event, which occurs before a control loses focus. However, this event occurs only when the CausesValidation property of the control that is about to receive the focus is set to True. In many cases, because the Validate event occurs before the focus is lost, it is more appropriate than the LostFocus event for data validation. For more information, see "Validating Control Data By Restricting Focus" in "Using Visual Basic's Standard
Some controls, such as the lightweight controls, cannot receive focus. Lightweight controls include the following:
Additionally, controls that are invisible at run time, such as the Timer control, cannot receive focus.