Finix
Finix

Reputation: 121

How to get an environment variable of a specified user from a Windows service?

I wrote a Windows service. It is running at the system level. I used the following code to get the logged in user's username. But I want to get an environment variable for that user session. How can I do that?

DWORD sessionId = WTSGetActiveConsoleSessionId();
qInfo() << "session id = " << sessionId;

wchar_t* ppBuffer[100];
DWORD bufferSize;
WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSUserName, ppBuffer, &bufferSize);
qInfo() << "Windows User Name = " << QString::fromWCharArray(*ppBuffer);

Upvotes: -1

Views: 995

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595837

Use WTSQueryUserToken() to get the logged in user token for the desired session ID, and then pass that token to CreateEnvironmentBlock() to get that user's environment variables.

You can then parse those strings as needed, or pass them (and the token) to CreateProcessAsUser() to launch a program as the user in the user's session.

Upvotes: 1

Related Questions