# GetWindowText Function

`Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long`

GetWindowText reads the title of a window (that is, its .Caption property). This function works with any window, not just those in your application! The text is put into the string variable passed as lpString. The function returns the length of the string returned, or 0 if an error occured.

hwnd
  The handle of the window to read the title of.
lpString
  Fixed-length string that receives the title of the window.
cch
  The length in characters of lpString.

Example:

    ' Read the number of characters in the title of Form1
    n = GetWindowTextLength(Form1.hWnd)
    ' Create a string of n+1 to receive the title (to allow for the ending vbNullChar
    buffer = Space(n + 1)
    ' Read the title
    x = GetWindowText(Form1.hWnd, buffer, n + 1)
    Debug.Print Left(buffer, x)  ' drop the vbNullChar

Related Calls: GetWindowTextLength, SetWindowText
Category: Windows
Back to the index.