簡體   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