在Windows系统上以C++打印出当前活动用户的环境变量

在Windows系统上以C++打印出当前活动用户的环境变量,代码如下(QT环境):

 

[cpp] view plain copy
 
  1. void getEnvironmentVariables()  
  2. {  
  3.     DWORD sessionId = WTSGetActiveConsoleSessionId();  
  4.     qInfo() << "Session ID = " << sessionId;  
  5.   
  6.     HANDLE token;  
  7.     if (!WTSQueryUserToken(sessionId, &token))  
  8.     {  
  9.         qCritical() << "Failed to get the user token of session " << sessionId;  
  10.     }  
  11.   
  12.   
  13.     wchar_t* pEnv = NULL;  
  14.     if (CreateEnvironmentBlock((void**)&pEnv, token, TRUE))  
  15.     {  
  16.         while (*pEnv) {  
  17.             // printf("%ls\n", pEnv);  
  18.             qInfo() << QString::fromWCharArray(pEnv);  
  19.             pEnv += wcslen(pEnv) + 1;  
  20.         }  
  21.     }  
  22. }  


以上是打印当前活动用户(active user)的。

 

如果仅仅是是打印当前进程所处环境的环境变量,见Visual Studio的代码如下:

 

[cpp] view plain copy
 
    1. #include <Windows.h>  
    2. #include <UserEnv.h>  
    3. #include <assert.h>  
    4.   
    5. #include <stdio.h>  
    6.   
    7. #pragma comment(lib, "userenv.lib")  
    8.   
    9. int main()  
    10. {  
    11.     HANDLE hToken = NULL;  
    12.     BOOL ok = OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hToken);  
    13.     assert(ok);  
    14.   
    15.     wchar_t* penv = L"";  
    16.     ok = CreateEnvironmentBlock((void**)&penv, hToken, TRUE);  
    17.     assert(ok);  
    18.   
    19.     while (*penv) {  
    20.         printf("%ls\n", penv);  
    21.         penv += wcslen(penv) + 1;  
    22.     }  
    23.     return 0;  
    24. }  

 

 

http://blog.csdn.net/nirendao/article/details/52040232

posted @ 2017-08-06 23:49  findumars  Views(722)  Comments(0Edit  收藏  举报