Determining Whether TAB or Mouse Gave a VB Control the Focus

ID Number: Q75411

1.00

WINDOWS

Summary:

You can determine whether a Visual Basic control received the focus

from a mouse click or a TAB keystroke by calling the Windows API

function GetKeyState in the control's GotFocus event procedure. By

using GetKeyState to check if the TAB key is down, you can determine

if the user tabbed to the control; if the TAB key was not used (and

the control does not have an access key), the user must have clicked

on the control with the mouse to set the focus.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

The GetKeyState Windows API function takes an integer parameter

containing the virtual key code for the desired key states.

GetKeyState returns an integer. If the return value is negative, the

key has been pressed.

The following is a code example. To use this example, start with a new

project in Visual Basic. Add a text box and a command button to Form1.

Enter the following code in the project's GLOBAL.BAS module:

'Global Module

Declare Function GetKeyState% Lib "User" (ByVal nVirtKey%)

Global Const VK_TAB = 9

Add the following code to the GotFocus event procedure for the Text1

text box control:

Sub Text1_GotFocus()

If GetKeyState(VK_TAB) < 0 Then

Text1.SelStart = 0

Text1.SelLength = Len(Text1.Text)

Else

Text1.SelLength = 0

End If

End Sub

Run the program. If you use the TAB key to move the focus from the

command button to the text box, you should see the text in the text

box selected. If you change the focus to the text box by clicking on

it with the mouse, the text will not be selected.

If the control has an access key (assigned by using an ampersand [&]

in the control's caption property), then you may also want to check

the state of the virtual ALT key using GetKeyState to see if the user

changed the focus using the access key. The virtual key code for ALT,

actually known as VK_MENU, is 12.

Additional reference words: 1.00