Search code examples
c++autoit

WinKill() source code


Can somebody share source code of WinKill() from AutoIt?

I want to know how it works with messages (yes/no/cancel) to be sure it's handled properly. I want to use it to clean desktop from unexpected pop-up windows.


Solution

  • As we can see below in the source code taken from the latest open source release of AutoIt (when it used to be open-source) and available here, the function sends WM_CLOSE message to the window. If the window doesn't get closed on 500ms, then it kills the process that created the window.

    ///////////////////////////////////////////////////////////////////////////////
    // WinKill()
    // Closes a window - uses more force than WinClose
    ///////////////////////////////////////////////////////////////////////////////
    
    AUT_RESULT AutoIt_Script::F_WinKill(VectorVariant &vParams, Variant &vResult)
    {
        Win_WindowSearchInit(vParams);
    
        if (Win_WindowSearch() == false)
            return AUT_OK;                          // Required window not found
    
        Util_WinKill(m_WindowSearchHWND);
        Util_Sleep(m_nWinWaitDelay);                // Briefly pause before continuing
    
        return AUT_OK;
    
    } // WinKill()
    
    ///////////////////////////////////////////////////////////////////////////////
    // Util_WinKill()
    //
    // Closes a window with extreme predjudice
    //
    ///////////////////////////////////////////////////////////////////////////////
    
    void Util_WinKill(HWND hWnd)
    {
        DWORD      dwResult;
    
        LRESULT lResult = SendMessageTimeout(hWnd, WM_CLOSE, 0, 0, SMTO_ABORTIFHUNG, 500, &dwResult);   // wait 500ms
    
        if( !lResult )
        {
            // Use more force - Mwuahaha
    
            // Get the ProcessId for this window.
            DWORD   pid;
            GetWindowThreadProcessId( hWnd, &pid );
    
            // Open the process with all access.
            HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    
            // Terminate the process.
            TerminateProcess(hProcess, 0);
    
            CloseHandle(hProcess);
        }
    
    } // Util_WinKill()