Get Current Username in C++ on Windows

Get current username in C++ on Windows

Use the Win32API GetUserName function. Example:

#include <windows.h>
#include <Lmcons.h>

char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);

How do I get the current username in .NET using C#?

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

Get current user name under Windows

You can use GetUserName

#include <windows.h>
#include <Lmcons.h>

char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);

C++ Microsoft example to get and display the user name doesn't compile

Win32 API provide what you need. The function GetUserNameW and GetComputerNameW are exactly what you need and the usage is very simple. Here a example that works:

#include <iostream>
#include <string>
#include <windows.h>
#include <Lmcons.h>

std::wstring getUsername() {
wchar_t username[UNLEN + 1];
DWORD username_len = UNLEN + 1;
GetUserNameW(username, &username_len);
return username;
}

std::wstring getComputerName() {
wchar_t computerName[UNLEN + 1];
DWORD computerName_len = UNLEN + 1;
GetComputerNameW(computerName, &computerName_len);
return computerName;
}

int main()
{
std::wcout << L"Username is : " << getUsername() << std::endl;
std::wcout << L"Computer name is : " << getComputerName() << std::endl;
return 0;
}


Related Topics



Leave a reply



Submit