Trim function, Unexpected results

cecil
StarLounger
Posts: 98
Joined: 09 Sep 2010, 16:01

Trim function, Unexpected results

Post by cecil »

I am calling an API function

Code: Select all

Private Declare Function GetUserName Lib "advapi32.dll" _
    Alias "GetUserNameA" _
    (ByVal lpbuffer As String, nsize As Long) As Long

Public Function GetUN() As String
    Dim lpbuffer As String * 30
    Dim nsize As Long
    Dim result As Long
    nsize = 30
    result = GetUserName(lpbuffer, nsize)
    If result Then
        GetUN = Trim(lpbuffer)
    Else
        GetUN = "Error"
    End If
End Function
I was sure that this worked in Windows 7 32 bit. However, in Windows 8.1 64 bit, the Trim function does not trim. I get a 30 character string. The following snippet returns 0 (zero) for the whitespace.

Code: Select all

   
     s = GetUN
    
    For x = 1 To Len(s)
        Debug.Print Asc(Mid(s, x, 1))
    Next x
For example, if the user name is AAAA, I get 65,65,65,65,0,0,0,0, ...

If I change the code by adding
lpbuffer = Space(30)

then the loop returning the ASCII coded returns 65,65,65,65,0. The API call is still returning one null character, but Trim does not trim it.

What did I miss. Thanks

User avatar
HansV
Administrator
Posts: 78236
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Trim function, Unexpected results

Post by HansV »

It has never worked that way. Windows API functions return a string of the exact length specified (30 in your example), with the actual value padded by ASCII 0 characters. So you have to use InStr to find the first occurrence of ASCII 0, and extract the part to the left of it. It has been this way since the earliest versions of Windows.

Code: Select all

Public Function GetUN() As String
    Dim lpbuffer As String * 30
    Dim nsize As Long
    Dim result As Long
    nsize = 30
    result = getUserName(lpbuffer, nsize)
    If result Then
        GetUN = Left(lpbuffer, InStr(lpbuffer, vbNullChar) - 1)
    Else
        GetUN = "Error"
    End If
End Function
Best wishes,
Hans

User avatar
rory
5StarLounger
Posts: 817
Joined: 24 Jan 2010, 15:56

Re: Trim function, Unexpected results

Post by rory »

Since nsize is adjusted to match the length of the return, you can also just use:

Code: Select all

        GetUN = left$(lpbuffer, nsize - 1)
Regards,
Rory

User avatar
HansV
Administrator
Posts: 78236
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Trim function, Unexpected results

Post by HansV »

Good point, thanks.
Best wishes,
Hans