我正在尝试制作一个程序,该程序通过给定的进程ID检测到进程终止。但是我不能给回调函数任何参数。我怎样才能做到这一点? 谢谢。
void CALLBACK WaitOrTimerCallback(
_In_ PVOID lpParameter,
_In_ BOOLEAN TimerOrWaitFired,
DWORD processID)
{
MessageBox(0, L"The process has exited.", L"INFO", MB_OK);
std::cout << processID << std::endl;
return;
}
int main()
{
DWORD dwProcessID = 1234;
HANDLE hProcHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessID);
HANDLE hNewHandle;
RegisterWaitForSingleObject(&hNewHandle, hProcHandle, WaitOrTimerCallback(?, ?, dwProcessID), NULL, INFINITE, WT_EXECUTEONLYONCE);
}
答案 0 :(得分:3)
RegisterWaitForSingleObject()
有一个Context
参数,正是为了将用户定义的数据传递给回调。例如:
void CALLBACK WaitOrTimerCallback(
_In_ PVOID lpParameter,
_In_ BOOLEAN TimerOrWaitFired)
{
DWORD dwProcessID = reinterpret_cast<DWORD>(lpParameter);
MessageBox(0, L"The process has exited.", L"INFO", MB_OK);
std::cout << dwProcessID << std::endl;
}
int main()
{
DWORD dwProcessID = 1234;
HANDLE hProcHandle = OpenProcess(SYNCHRONIZE, FALSE, dwProcessID);
if (hProcHandle)
{
HANDLE hNewHandle;
if (RegisterWaitForSingleObject(&hNewHandle, hProcHandle, &WaitOrTimerCallback, reinterpret_cast<void*>(dwProcessID), INFINITE, WT_EXECUTEONLYONCE))
UnregisterWait(hNewHandle);
CloseHandle(hProcHandle);
}
return 0;
}
尽管在此特定示例中,在RegisterWaitForSingleObject()
足够的情况下将INFINITE
与WaitForSingleObject()
超时一起使用是过大的:
int main()
{
DWORD dwProcessID = 1234;
HANDLE hProcHandle = OpenProcess(SYNCHRONIZE, FALSE, dwProcessID);
if (hProcHandle)
{
if (WaitForSingleObject(hProcHandle, INFINITE) == WAIT_OBJECT_0)
{
MessageBox(0, L"The process has exited.", L"INFO", MB_OK);
std::cout << dwProcessID << std::endl;
}
CloseHandle(hProcHandle);
}
return 0;
}
RegisterWaitForSingleObject()
当您要在后台继续执行其他操作时要在后台异步等待对象时,应使用
{{1}}。不要等待等待操作。当对象发出信号时,操作系统会通知您。