在CSDN论坛上看到有帖子在问如何获得计算机名称及用户名。这个其实非常简单。二个函数——GetComputerName和GetUserName就搞定了。其函数原型如下:
一.GetComputerName
//By MoreWindows-(http://blog.csdn.net/MoreWindows)
BOOLWINAPI GetComputerName(
__out LPTSTRlpBuffer,
__in_out LPDWORDlpnSize
);
二.GetUserName
//By MoreWindows-(http://blog.csdn.net/MoreWindows)
BOOLWINAPI GetUserName(
__out LPTSTRlpBuffer,
__in_out LPDWORDlpnSize
);
直接上代码算了,这参数光看名字就知道什么意思了。
- // VC++得到计算机名称和用户名称
- // http://blog.csdn.net/morewindows/article/details/8659417
- //By MoreWindows-(http://blog.csdn.net/MoreWindows)
- #include <windows.h>
- #include <stdio.h>
- int main()
- {
- printf(" VC++得到计算机名称和用户名称 \n");
- printf(" -- By MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
- const int MAX_BUFFER_LEN = 500;
- char szBuffer[MAX_BUFFER_LEN];
- DWORD dwNameLen;
- dwNameLen = MAX_BUFFER_LEN;
- if (!GetComputerName(szBuffer, &dwNameLen))
- printf("Error %d\n", GetLastError());
- else
- printf("计算机名为: %s\n", szBuffer);
- dwNameLen = MAX_BUFFER_LEN;
- if (!GetUserName(szBuffer, &dwNameLen))
- printf("Error %d\n", GetLastError());
- else
- printf("当前用户名为:%s\n", szBuffer);
- return 0;
- }
运行结果如下: