【发布时间】:2023-04-03 19:13:02
【问题描述】:
我正在开发一个应用程序,它可以创建多个桌面并让用户能够在他当前使用的桌面下启动他想要的任何应用程序。
当该桌面关闭时(使用组合键),我想关闭在该桌面下打开的所有应用程序。为了做到这一点,我使用EnumProcesses 函数枚举所有进程,并根据 EnumProcesses 使用OpenProcess 函数返回的每个进程标识符检索一个句柄。使用GetThreadId,我检索了用作GetThreadDesktop函数参数的线程标识符,并将返回的句柄与我桌面上的句柄进行比较,这样我就可以找出进程在哪个桌面上运行。
至少在理论上,这是可行的,因为对于每个进程标识符,OpenProcess 函数都会返回一个无效的 GetThreadId 句柄(错误代码 6)。我以管理员身份运行应用程序并启用了 SeDebugPrivilege 权限。
我不明白为什么返回的句柄总是无效,这是我使用的代码:
void iterateProcesses(HDESK threadDesktop)
{
EnableDebugPriv(); // functions enables the SeDebugPrivilege privilege
int found = 0;
int wanted = 0;
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
cProcesses = cbNeeded / sizeof(DWORD);
for (i = 0; i < cProcesses; i++)
{
if (aProcesses[i] != 0)
{
found++;
if (GetThreadDesktop(checkProcess(aProcesses[i])) == threadDesktop)
{
wanted++;
}
}
}
}
DWORD checkProcess(DWORD processID)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, processID);
GetLastError(); // if in the manifest file under 'UAC execution level'
// the application does not requests for administrator rights
// GetLastError() will return code 5 (access denied)
DWORD dwThreadId = GetThreadId(hProcess);
GetLastError(); // return code 6 (ERROR_INVALID_HANDLE)
// dwThreadId returned is always 0 because the handle is not valid
CloseHandle(hProcess);
return dwThreadId;
}
【问题讨论】: