【发布时间】:2018-04-16 03:00:31
【问题描述】:
我想在 C++ 中创建一个 Windows 服务,以便在用户每次登录时以管理员身份启动我的程序而不弹出 UAC 窗口
因为这是我第一次这样做,所以我使用了这里的项目: https://code.msdn.microsoft.com/windowsapps/CppWindowsService-cacf4948/view/SourceCode
我将 CppWindowsService.cpp 中的第 74 行编辑为:
InstallService(
SERVICE_NAME, // Name of service
SERVICE_DISPLAY_NAME, // Name to display
SERVICE_AUTO_START, // Service start type
SERVICE_DEPENDENCIES, // Dependencies
0, // Service running account
SERVICE_PASSWORD // Password of the account
);
并在 SampleService.cpp 第 101 行的工作线程中添加了一些代码,变成这样:
void CSampleService::ServiceWorkerThread(void)
{
// Periodically check if the service is stopping.
while (!m_fStopping)
{
// Perform main service function here...
HANDLE hToken = NULL, dToken;
WTSQueryUserToken(WTSGetActiveConsoleSessionId(), &hToken);
DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, 0, SecurityIdentification, TokenPrimary, &dToken);
STARTUPINFO stinfo = { 0 };
PROCESS_INFORMATION pinfo = { 0 };
stinfo.cb = sizeof(stinfo);
stinfo.lpDesktop = L"winsta0\\default";
LPVOID pEnv = 0;
CreateEnvironmentBlock(&pEnv, dToken, 0);
CreateProcessAsUserW(dToken, L"F:\\test.exe",0, 0, 0, 0,CREATE_NEW_CONSOLE, pEnv, 0, &stinfo, &pinfo);
::Sleep(2000); // Simulate some lengthy operations.
}
// Signal the stopped event.
SetEvent(m_hStoppedEvent);
}
位于 F 驱动器的 test.exe 显示一个消息框,但是当我尝试从服务运行它时,虽然我可以轻松地使用 CreateProcess 从普通程序中执行它,但什么也没有发生
编辑:我也尝试在 CreateProcessAsUser 中放置一个命令行,但没有任何反应
【问题讨论】:
-
查看
CreateProcessAsUserW的返回值,如果是FALSE调用GetLastError找出问题所在 -
你叫什么
DuplicateTokenEx? -
和
DestroyEnvironmentBlock必须是 -
不要复制token,创建进程后关闭
hToken。希望您在完成后也关闭pinfo返回的进程和线程句柄。 -
这里更大的问题是设计错误。 “每次用户登录时以管理员身份启动我的程序”。服务在特定用户登录之前启动。
标签: c++ windows winapi service