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

心不动则不痛 提交于 2019-12-11 18:06:20

问题


I have the following code that opens an application using CreateProcess and waits for it for a few seconds and then closes it if its not been closed. The same code works OK on notepad++ for example, but not when I try to open 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 does not get called and when I remove the if statement and call EnumWindows(&SendWMCloseMsg, pi.dwProcessId);, it still does not find the correct processId.

What Am I doing wrong with this code and how to address this issue?

I'm using Windows 10, 64bit and VS2015


回答1:


The answer is that the process you started with CreateProcess created a bunch of other processes - and then quit.

Your WaitForSingleObject completes successfully, and your program ends.



来源:https://stackoverflow.com/questions/50327232/waitforsingleobject-works-when-trying-to-open-notepad-but-returns-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!