// Description:
// Function gets user name.
void CollectUserName() {
// Name format, we need the longest, most descriptive one.
EXTENDED_NAME_FORMAT name_format = NameSamCompatible;
// Local memory pointer to store user name.
TCHAR *user_name = NULL;
// This will hold user_name size in TCHARs on input and required size
// of user_name on output.
ULONG user_name_size = 1;
ULONG required_size;
// Will give GetUserNameEx() minimal buffer. Not sure if it will accept
// 0-length buffer (this case is not documented).
user_name = new (nothrow) TCHAR[1];
HRESULT result = GetUserNameEx(name_format, user_name, &user_name_size);
required_size = user_name_size;
delete [] user_name;
user_name = NULL;
// Allocating block of memory of the required size.
user_name = new (nothrow) TCHAR[user_name_size];
result = GetUserNameEx(name_format, user_name, &user_name_size);
cout << required_size << user_name_size;
// Output: 22 11 - for Character Encoding set to "Not Set"
// 11 11 - for Character Encoding set to "Use Unicode Chracter Set"
}