简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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