当我运行我的程序时发生了一些奇怪的事情。当我在 VS 2010 中使用“不调试启动”选项运行它时,OpenProcess 照常返回进程句柄,但是当我在 Windows 资源管理器中运行我的程序时,OpenProcess 总是返回 0?!我调用了 GetLastError,它在这两种情况下都返回 6 (INVALID_HANDLE_VALUE)。我正在使用 Windows XP SP3 有人可以帮帮我吗?这是我写的代码:
HANDLE GetProcessHandle(TCHAR* szProcessName)
{
//Get the snapshot of all processes in the system
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
if (hSnap == INVALID_HANDLE_VALUE)
{
return INVALID_HANDLE_VALUE;
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
//Get the information of the first process
if (!Process32First(hSnap, &pe32))
{
CloseHandle(hSnap);
return INVALID_HANDLE_VALUE;
}
//Loop through all processes
do
{
if (_tcscmp(szProcessName, pe32.szExeFile) == 0)
{
//Got the process ID
CloseHandle(hSnap);
printf("sz = %s; exe = %s; pid = %d\n", szProcessName, pe32.szExeFile, pe32.th32ProcessID);
//Error here, correct PID was found in both case
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
}
}
while (Process32Next(hSnap, &pe32));
CloseHandle(hSnap);
return INVALID_HANDLE_VALUE;
}