//https://my.oschina.net/macwe/blog/348656
//Windows:服务程序用当前登录用户来执行函数
#include <Wtsapi32.h>
#pragma comment(lib, "Wtsapi32.lib")
BOOL CurrentUserIsLocalSystem()
{
BOOL bIsLocalSystem = FALSE;
PSID psidLocalSystem;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
BOOL fSuccess = ::AllocateAndInitializeSid(&ntAuthority, 1, SECURITY_LOCAL_SYSTEM_RID,
0, 0, 0, 0, 0, 0, 0, &psidLocalSystem);
if (fSuccess)
{
fSuccess = ::CheckTokenMembership(0, psidLocalSystem, &bIsLocalSystem);
::FreeSid(psidLocalSystem);
}
return bIsLocalSystem;
}
HANDLE hTokenUser = NULL;
DWORD ConsoleSessionId = 0;
BOOL bImpersonateLoggedOnUser = FALSE;
char userName[256] = {0};
DWORD userNameLen = sizeof(userName);
GetUserName(userName, &userNameLen);
if (0 == stricmp("SYSTEM", userName))
{
// 得到当前激活用户的会话ID
ConsoleSessionId = WTSGetActiveConsoleSessionId();
// 得到当前登录用户的令牌
if (WTSQueryUserToken(ConsoleSessionId, &hTokenUser))
{
// 模仿成当前登录用户
bImpersonateLoggedOnUser = ImpersonateLoggedOnUser(hTokenUser);
}
}
// 终止模拟,返回
if (bImpersonateLoggedOnUser)
{
RevertToSelf();
}
//微软给的代码可以模拟客户端 ——C++ 中启动交互式客户端进程
https://docs.microsoft.com/zh-cn/previous-versions/aa379608(v=vs.85)
