[VBA × Windows API] How to Use the GetWindowText Function

GetWindowText Function

The GetWindowText function retrieves the text shown in the title bar (the caption) of a specified window. For example, calling GetWindowText against a VBA UserForm window returns the same value you’d get by reading UserForm.Caption.

Two functions are closely related to GetWindowText: GetWindowTextLength, which returns the length of the caption, and its mirror image SetWindowText, which writes a new caption to a given window.

 

Usage

Before calling GetWindowText, you must declare it at the top of your module.
Without the declaration the function cannot be used and will raise an error, so don’t forget it.

The declaration differs depending on whether your Office/VBA host is 32-bit or 64-bit. Place one of the following near the top of your module (just after Option Explicit) to make the function available inside that module.

icon-code 64-bit

Declare PtrSafe Function GetWindowText Lib “user32" Alias “GetWindowTextA" _
(ByVal hwnd As LongPtr, ByVal lpString As String, ByVal cch As Long) As Long

icon-code 32-bit

Declare Function GetWindowText Lib “user32" Alias “GetWindowTextA" _
(ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

If you are not sure which one to use, paste the following block at the top of your module. It automatically selects the correct declaration at compile time.
In the VBE, the unused branch may be shown in red, but this does not affect execution.

#If VBA7 Then
    Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As LongPtr, ByVal lpString As String, ByVal cch As Long) As Long
#Else
    Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
#End If

You can also prefix the declaration with Private or Public to control its scope.

Private Declare PtrSafe Function … : callable only within the current module
Public Declare PtrSafe Function … : callable from outside the module

 
 

Syntax

The syntax of the GetWindowText function is as follows.

icon-code GetWindowText function

lRet = GetWindowText(hWnd, lpString, nMaxCount)

Arguments

hWnd (64-bit: LongPtr / 32-bit: Long)

Handle to the window whose caption you want to read.
There are several APIs that can produce a window handle, including FindWindow, GetActiveWindow, GetNextWindow, and GetParent.
The variable type depends on whether you’re running 32-bit or 64-bit VBA, so be careful when declaring the variable that holds the handle.
 

lpString (String)

An empty fixed-length string that the API will write the caption into.
In VBA, String variables are normally variable-length, so “fixed-length string" might sound unfamiliar. The difference is exactly what the name suggests: a fixed-length string has a predetermined size — that is, a fixed number of characters it can hold.

To declare a fixed-length string in VBA, use the form Dim x As String * 7. With that declaration the variable can hold at most 7 characters; if you assign a shorter string, the remainder is padded with null/space characters to fill all 7 slots.

So for this argument, you simply declare a fixed-length string large enough to hold the entire caption and pass it in. If the buffer is too small, the retrieved caption may be truncated, so make it generous. (A length of about 100 characters is enough for almost any window caption.)
You can also use GetWindowTextLength to size the buffer precisely in advance.
 

nMaxCount (Long)

The maximum number of characters of the caption to copy.
As with lpString, setting this too small can truncate the result, so make it generous. The common idiom in VBA is to call Len on the fixed-length buffer and pass that value here.
 

Return value

lRet (Long)

On success, the return value is the number of characters actually copied to the buffer.
(Note: multi-byte / full-width characters can be counted as 2 characters each, so the return value may not equal the number of “visible" characters.)
On failure, the return value is 0.

 

Sample Code

The sample below combines FindWindow with GetWindowText to retrieve the caption of a specific window. As written, it returns the caption of whichever Excel window is currently in the front. By replacing the class name "XLMAIN" you can target any other application.
For details on class names, see the FindWindow and GetClassName pages.

Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As LongPtr, ByVal lpString As String, ByVal cch As Long) As Long

Sub main()

    Dim hwnd As LongPtr
    Dim lRet As LongPtr
    Dim sBuf As String * 100
    Dim sCap As String
    
    ' Get the handle of the frontmost Excel window
    hwnd = FindWindow("XLMAIN", vbNullString)
    
    ' Get the caption of that handle (into a fixed-length string)
    lRet = GetWindowText(hwnd, sBuf, Len(sBuf))
    
    ' Trim the unused buffer part
    sCap = Left(sBuf, InStr(sBuf, vbNullChar) - 1)
    
    ' Print the retrieved caption to the Immediate window
    Debug.Print sCap
    
End Sub

The most important line in this sample is the one labelled “Trim the unused buffer part."
After GetWindowText returns, the fixed-length buffer sBuf holds the window’s caption — but if you inspect it in the VBE Locals window, you’ll see a trail of mysterious “・" characters padding the end. Those “・" characters are vbNullChar in VBA.

Before using the value, you need to strip those padding null characters. There are several ways to do it, but the approach in the sample is the simplest and most general — it’s the familiar VBA pattern of “take everything to the left of a given character," applied to the first vbNullChar in the buffer.

You could also use the return value of GetWindowText (which is the character count) to truncate the buffer, but as noted above, full-width characters distort that count, so an extra adjustment step is usually needed.

 

icon-share-square VBA × Windows API Index

For other Windows API functions, please also refer to the index page below.

icon-share-square Reference

Microsoft official: GetWindowTextA function (winuser.h) — Win32 apps

Excel,VBA,Windows API