我有以下代码使用 CreateProcess 打开一个应用程序并等待它几秒钟,然后如果它没有关闭则关闭它。例如,相同的代码在记事本++上工作正常,但当我尝试打开 Firefox.exe 时却不行
BOOL CALLBACK SendWMCloseMsg(HWND hwnd, LPARAM lParam)
{
//never gets called when opening Firefox.exe
DWORD dwProcessId = 0;
GetWindowThreadProcessId(hwnd, &dwProcessId);
if (dwProcessId == lParam)
SendMessageTimeout(hwnd, WM_CLOSE, 0, 0, SMTO_ABORTIFHUNG, 30000, NULL);
return TRUE;
}
int main()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
WCHAR szFilename[] = L"C:\\Program Files\\Mozilla Firefox\\firefox.exe";
if (CreateProcess(NULL,
szFilename,
NULL,
NULL,
FALSE,
CREATE_DEFAULT_ERROR_MODE,
NULL,
NULL,
&si,
&pi))
{
CloseHandle(pi.hThread);
WaitForInputIdle(pi.hProcess, INFINITE);
auto a = WaitForSingleObject(pi.hProcess, 30000);
if (a == WAIT_TIMEOUT)
{
EnumWindows(&SendWMCloseMsg, pi.dwProcessId);
if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_TIMEOUT)
{
//never gets here.
TerminateProcess(pi.hProcess, 0);
}
}
//a vlaue is 0 and it never gets in the if statement.
CloseHandle(pi.hProcess);
}
return 0;
}
SendWMCloseMsg
没有被调用,当我删除 if 语句并调用EnumWindows(&SendWMCloseMsg, pi.dwProcessId);
时,它仍然找不到正确的 processId。
我对这段代码做错了什么以及如何解决这个问题?
我正在使用 Windows 10、64 位和 VS2015