![]() |
![]() |
|||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
|
Q: Get the login name of the current userAnswerCall the GetUserName API function. void __fastcall TForm1::Button1Click(TObject *Sender) { DWORD dwSize = 0; // Determine how many chars we need to store user name GetUserName(NULL, &dwSize); // create a buffer that is big enough char *szBuf = new char[dwSize]; szBuf[0] = '\0'; // Read the user name and place it in a label GetUserName(szBuf, &dwSize); Label1->Caption = szBuf; delete [] szBuf; } Note: The API function copies the user name into an array of chars. After retrieving the user name, the code above assigns the character buffer to a label caption. The label copies the string. It does not assume ownership of your character buffer. The code is still responsible for deleting the character buffer, not the TLabel. Note: GetUserName copies characters into a buffer that you supply. The second argument to the function is a pointer to a DWORD. The value of the DWORD tells the API how many bytes your buffer can hold, including the null terminator. If your buffer is not large enough to hold the string, the API writes the required size back into the DWORD. This FAQ uses a common technique that calls the API function twice. On the first call, a NULL string is passed and the DWORD is initialized to zero. This guarantees the function will fail. The API responds by writing the required buffer size into the DWORD without trying to copy the string. The required size is used to allocated a buffer. The code passes this buffer to the API function on the second call. This technique avoids guesswork in trying to determine the largest possible buffer that you would ever need. The following code would also work, although I prefer the first technique: void __fastcall TForm1::Button1Click(TObject *Sender) { DWORD dwSize = MAX_PATH+1; char szBuf[MAX_PATH+1]; szBuf[0] = '\0'; GetUserName(szBuf, &dwSize); Label1->Caption = szBuf; } | ||||||
All rights reserved. |