|
|
|
Most API function that return a string require that you pass a buffer where they can place the result as a null-terminated ANSI string (a.k.a. ASCIIZ string). The calling code must then extract the string by taking all the characters up to the first Chr$(0) character, if there is one. For example, this is the code that returns the caption of any window: |
Click here to copy the following block | Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal _ hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _ lParam As Any) As Long Private Const WM_GETTEXT = &HD
Dim buffer As String, i As Long, winText As String buffer = Space$(512) SendMessage hWnd, WM_GETTEXT, Len(buffer), ByVal buffer i = Instr(buffer, vbNullChar) If i Then winText = Left$(winText, i - 1) Else winText = "" End If |
Here is a more concise version that ensures that the InStr function doesn't fail to find a null character, and eliminates the need for the i and buffer local variables: |
Many API functions don't even require that you search for the null-character, because they return the actual number of valid characters. For example, it seems that this is the best way to determine the Windows' SYSTEM directory: |
However, the SDK docs tell that the GetSystemDirectory function returns the number of the characters in the result. This lets you get rid of the InStr function. And you can also get rid of the Space$ function by re-inserting a fixed-length local variable: |
Finally, here's the shortest version possible, that doesn't even need the length local variable and pass the result of the API function directly to the 2nd argument of the Left function. I don't claim that this is a good programming style, because it makes the code rather obscure even to those that know how the API works, and also because it might not work in other versions of VB (I tested it only under VB6). However, it's good to know that you can sometimes write extremely concise code even in VB: |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|