Wrap It Up
Face it. Passing empty string buffers with lengths is un-Basic; the Basic Way is to simply return the string. You can choose to put up with the C style of strings every time you call GetWindowText or a similar function, or you can deal with it once by wrapping the Windows API function in a Basic function. Here’s how to do this for GetWindowText:
Function WindowTextFromWnd(ByVal hWnd As Long) As String
Dim c As Integer, s As String
c = GetWindowTextLength(hWnd)
If c <= 0 Then Exit Function
s = String$(c, 0)
c = GetWindowText(hWnd, s, c + 1)
WindowTextFromWnd = s
End Function
The trick in this type of function is to decide the length of the string to allocate. GetWindowTextLength and GetWindowText are the only function pair in the Windows API in which one returns the length expected by the other. Even in this case, it might be more efficient to assume that no window title will be larger than 255 bytes and to allocate that size without checking the actual size. The string will just be thrown away when the function returns, so no harm is done if you allocate too much space. Worst case is that someone will use a window title 300 bytes long and that you’ll truncate it to 255. Serves them right.
The Windows API offers many variations on this theme. When the string is informational, the function usually truncates if you don’t provide a large enough buffer. If the string is a filename, the function copies nothing but returns the actual size of the data (a truncated filename would be worse than no name at all). If you get back more than you put in, you need to allocate a bigger string and call again. Sometimes, the Windows API documentation clearly states the maximum size you need to pass in; other times, you can guess. For example, if a function returns a full file specification, you can safely pass the maximum Win32 path size—260 characters.