繁体   English   中英

尝试打开Notepad ++时,Waitforsingleobject起作用,但使用Firefox立即返回

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

我有以下代码,这些代码使用CreateProcess打开一个应用程序,等待它几秒钟,如果未关闭,则将其关闭。 例如,相同的代码在notepad ++上可以正常运行,但是在我尝试打开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成功完成,并且程序结束。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM