在Windows系统上以C++打印出当前活动用户的环境变量,代码如下(QT环境):
void getEnvironmentVariables()
{
DWORD sessionId = WTSGetActiveConsoleSessionId();
qInfo() << "Session ID = " << sessionId;
HANDLE token;
if (!WTSQueryUserToken(sessionId, &token))
{
qCritical() << "Failed to get the user token of session " << sessionId;
}
wchar_t* pEnv = NULL;
if (CreateEnvironmentBlock((void**)&pEnv, token, TRUE))
{
while (*pEnv) {
// printf("%ls\n", pEnv);
qInfo() << QString::fromWCharArray(pEnv);
pEnv += wcslen(pEnv) + 1;
}
}
}
以上是打印当前活动用户(active user)的。
如果仅仅是是打印当前进程所处环境的环境变量,见Visual Studio的代码如下:
#include <Windows.h>
#include <UserEnv.h>
#include <assert.h>
#include <stdio.h>
#pragma comment(lib, "userenv.lib")
int main()
{
HANDLE hToken = NULL;
BOOL ok = OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hToken);
assert(ok);
wchar_t* penv = L"";
ok = CreateEnvironmentBlock((void**)&penv, hToken, TRUE);
assert(ok);
while (*penv) {
printf("%ls\n", penv);
penv += wcslen(penv) + 1;
}
return 0;
}