| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 
 | #ifdef UNICODE
 bool CreateProcessWithUser(const std::wstring& exePath, const std::wstring& param, bool show)
 #else
 bool CreateProcessWithUser(const std::string& exePath, const std::string& param, bool show)
 #endif
 {
 HANDLE hToken = 0;
 HANDLE hNewToken = 0;
 LPVOID pEnvironment{ NULL };
 bool res{ false };
 int l = param.length();
 #ifdef UNICODE
 wchar_t* cmd = new wchar_t[l + 1];
 memcpy(cmd, param.c_str(), l * sizeof(wchar_t));
 cmd[l] = 0;
 #else
 char* cmd = new char[l + 1];
 memcpy(cmd, param.c_str(), l * sizeof(char));
 cmd[l] = 0;
 #endif
 
 do
 {
 if (!GetTokenWithProcessName(L"explorer.exe", hToken))
 {
 LOG_ERROR("GetTokenWithProcessName Error: %u", GetLastError());
 break;
 }
 if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL, SECURITY_MAX_IMPERSONATION_LEVEL, TokenPrimary, &hNewToken))
 {
 LOG_ERROR("DuplicateTokenEx Error: %u", GetLastError());
 break;
 }
 DWORD dwCreationFlag = NORMAL_PRIORITY_CLASS  | CREATE_UNICODE_ENVIRONMENT;
 
 if (!CreateEnvironmentBlock(&pEnvironment, hNewToken, FALSE))
 {
 LOG_ERROR("CreateEnvironmentBlock Error: %u", GetLastError());
 break;
 }
 STARTUPINFO si;
 PROCESS_INFORMATION pi;
 ZeroMemory(&si, sizeof(STARTUPINFO));
 si.cb = sizeof(STARTUPINFO);
 #ifdef UNICODE
 wchar_t desktop[] = L"winsta0\\default";
 #else
 char desktop[] = "winsta0\\default";
 #endif
 si.lpDesktop = desktop;
 si.dwFlags = STARTF_USESHOWWINDOW;
 if (show)
 {
 si.wShowWindow = SW_SHOW;
 }
 else
 {
 si.wShowWindow = SW_HIDE;
 }
 if (!CreateProcessAsUser(hNewToken, exePath.c_str(), cmd, 0, 0, FALSE, dwCreationFlag, pEnvironment, 0, &si, &pi))
 {
 #ifdef UNICODE
 std::string ansicmd = mm::Charset::UnicodeToANSI(cmd);
 std::string ansibat = mm::Charset::UnicodeToANSI(exePath.c_str());
 LOG_ERROR("CreateProcessAsUser error! LastError=%ld, %s, %s", GetLastError(), ansibat.c_str(), ansicmd.c_str());
 #else
 LOG_ERROR("CreateProcessAsUser error! LastError=%ld, %s, %s", GetLastError(), exePath.c_str(), cmd.c_str());
 #endif
 break;
 }
 res = true;
 } while (0);
 
 delete[] cmd;
 if (hToken)
 {
 CloseHandle(hToken);
 }
 if (hNewToken)
 {
 CloseHandle(hNewToken);
 }
 if (pEnvironment)
 {
 DestroyEnvironmentBlock(pEnvironment);
 }
 return res;
 }
 
 |