Jalaj

January 31, 2007

WinAPI : Getting Window Texts

Filed under: Visual Basic, WinAPI — Jalaj @ 4:24 am

Window Text of a window is the caption on the title bar if the window is a form, or the text contained it the window in question here is a control on some form. Getting a window text or setting it requires calling the SendMessage function (described in More on SendMessage) with messages WM_GETTEXT and WM_SETTEXT resp.

The same can be performed using the GetWindowText and SetWindowText functions, however with restrictions that though they can get/set text of Forms of some other applications, these functions cannot access controls that exist in other applications.

The GetWindowText function takes for input the handle to the window, the pointer to a buffer that will receive the text and the maximum number of characters from the window text to be copied to the buffer. The text received is stored as string terminating with NULL character, thus the string receiving the text should be initialised with length sufficient to accomodate otherwise the text received would be truncated.

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

For example your form can have the code as below for its Load event.

Private Sub Form_Load()

    Dim strWinText As String * 50
    GetWindowText Form1.hwnd, strWinText, Len(strWinText)
    MsgBox strWinText

End Sub

The SetWindowText function, on the other hand, allows you to change the window text given the handle to the window and the pointer to the NULL terminated string which is to be set as new text.

Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" ( _
     ByVal hwnd As Long, ByVal lpString As String) As Long

While the above functions rely on SendMessage function, the InternalGetWindowText (Windows 2000 and above) which is similar to GetWindowText, obtains the window text directly from the window structure associated with the handle. The text received is always stored as a unicode string.

Declare Function InternalGetWindowText Lib "user32" ( _
     ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

GetWindowTextLength function can be utilised to get the text length of the window text given the handle to the window. The function returns the length of the text in characters. If the window has no text the value returned is zero.

Public Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.