在windows平台下,使用GetUserName获取当前用户名,使用GetComputerName获取当前计算机名;
#include <iostream>
#include <windows.h>
#include <cstring>
#include <string>
#include "lm.h"
#pragma comment(lib,"netapi32.lib")
using namespace std;
// 多字节转string
string WCharToMByte(LPCWSTR lpcwszStr)
{
string str;
DWORD dwMinSize = 0;
LPSTR lpszStr = NULL;
dwMinSize = WideCharToMultiByte(CP_OEMCP, NULL, lpcwszStr, -1, NULL, 0, NULL, FALSE);
if (0 == dwMinSize)
{
return FALSE;
}
lpszStr = new char[dwMinSize];
WideCharToMultiByte(CP_OEMCP, NULL, lpcwszStr, -1, lpszStr, dwMinSize, NULL, FALSE);
str = lpszStr;
delete[] lpszStr;
return str;
}
string get_computer_name()
{
char buffer[512];
DWORD name_len=512;
string name;
GetComputerName((LPSTR)buffer,&name_len);
name.assign(buffer);
return name;
}
void Get_LogUser(string &strName)
{
TCHAR abyUserName[MAX_PATH] = { 0 };
DWORD dwSize = MAX_PATH;
::GetUserName(abyUserName, &dwSize);
LPUSER_INFO_3 bufptr = NULL;
NET_API_STATUS t3;
t3 = NetUserGetInfo(0, abyUserName, 3, (LPBYTE*)&bufptr);
if (t3 != NERR_Success)
{
return;
}
//全名不为空,就使用用户名的全名,为空就使用用户名
string strFullName = WCharToMByte(bufptr->usri3_full_name);
if (strFullName.empty())
{
strName = WCharToMByte(bufptr->usri3_name);
}
else
{
strName = WCharToMByte(bufptr->usri3_full_name);
}
NetApiBufferFree(bufptr);
bufptr = NULL;
}
int main()
{
TCHAR strBuffer[256] = { 0 };
DWORD dwSize = 256;
//GetUserName(strBuffer, &dwSize);
string computerName;
Get_LogUser(computerName);
cout << "当前用户名:" << computerName << endl;
return 0;
}