Declare Function GetFocus Lib "user32.dll" () As Long
GetFocus obtains a handle to the window in the calling thread that has the input focus. If another program has the input focus, however, this function will not work and will report an error.
If successful, the function returns a handle to the window that has the input focus. If an error occured, or if another program has the input focus, the function returns zero (use GetLastError to get the error code).
Print the title of the window that currently has the input focus, if our program has it. If not, inform the user that some other program has int focus. This is done whenever timer timCheck elapses, so to use this example, you must first place a timer named timCheck on a form window.
' This code is licensed according to the terms and conditions listed here. ' Declarations and such needed for the example: ' (Copy them to the (declarations) section of a module.) Public Declare Function GetFocus Lib "user32.dll" () As Long Public Declare Function GetWindowTextLength Lib "user32.dll" Alias "GetWindowTextLengthA" _ (ByVal hWnd As Long) As Long Public Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextA" (ByVal hWnd As Long, _ ByVal lpString As String, ByVal nMaxCount As Long) As Long ' *** Place the following code inside the form window. *** Private Sub timCheck_Timer() Dim hWnd As Long ' window that has the focus Dim wintext As String ' title of the window Dim textlen As Long ' length of the title ' First, see which window in the program, if any, has the input focus. hWnd = GetFocus() If hWnd = 0 Then Debug.Print "This program does not have the input focus." Else ' Get the title of the window that has the focus. textlen = GetWindowTextLength(hWnd) + 1 wintext = Space(textlen) textlen = GetWindowText(hWnd, wintext, textlen) ' Display the title, removing the terminating null. Debug.Print "The window titled '" & Left(wintext, textlen) & "' has the focus." End If End Sub
Back to the Function list.
Back to the Reference section.
Last Modified: December 17, 2000
This page is copyright © 2000 Paul Kuliniewicz. Copyright Information Revised October 29, 2000
Go back to the Windows API Guide home page.
E-mail: firstname.lastname@example.org Send Encrypted E-Mail
This page is at http://www.vbapi.com/ref/g/getfocus.html