Waitforsingleobject在尝试打开Notepad++时工作,但立即返回Firefox

Waitforsingleobject works when trying to open Notepad++ but returns immediately with Firefox

本文关键字:Firefox 返回 工作 Notepad++ Waitforsingleobject      更新时间:2023-10-16

我有以下代码,它使用 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

答案是你开始的流程CreateProcess创建了一堆其他进程 - 然后退出。

您的WaitForSingleObject成功完成,并且您的程序结束。