Search code examples
c++vbscriptwshcreatewindowex

Windows Script Host terminates when closing the created window


I created a wrapper function for CreateWindowEx API function and used it from a VBScript. This is the VBScript:

Dim Result, wcx(10) 'VARIANT ARRAY(10) - WNDCLASSEX

wcx(5) = WINAPI.WinAPI_LoadIcon(NULL, 32516)   'hIcon (IDI_INFORMATION)
wcx(6) = WINAPI.WinAPI_LoadCursor(NULL, 32649) 'hCursor (IDC_HAND)
wcx(7) = 3                                     'hbrBackground (COLOR_ACTIVECAPTION + 1)
wcx(9) = "DUMMY_CLASS"                         'lpszClassName
wcx(10) = WINAPI.WinAPI_LoadIcon(NULL, 32516)  'hIconSm (SAME as hIcon)

'PASS THE VARIANT ARRAY TO THE WRAPPER FUNCTION
Result = WINAPI.WinAPI_RegisterClassEx(wcx)

Dim Style: Style = CLng(&H00CF0000)     'WS_OVERLAPPEDWINDOW
Dim ExStyle: ExStyle = CLng(&H00000100) 'WS_EX_WINDOWEDGE

If CLng(Result) > 0 Then
    'CREATE THE WINDOW
    Result = WINAPI.WinAPI_CreateWindowEx(ExStyle, "DUMMY_CLASS", "Hello World!", Style, 875, 6, 400, 300, NULL, NULL, NULL, NULL)
    WINAPI.WinAPI_ShowWindow Result, 5
    WScript.Echo "CreateWindowEx returned 0x" + CStr(UCase(Hex(Result)))
End If

The window creates as expected and displays fine. But I am wondering why Windows Script Host terminates when I click the created window's close button.

And I tested CreateWindowEx using AutoIt, when I closed the created window, AutoIt3.exe is not terminated and it continued running script unlike Windows Script Host.

I like to keep Windows Script Host running even I close the created window.

Isn't there anyway to achieve what I want and I like to know what is the reason for this to happen with Windows Script Host.


Solution

  • I fixed the problem by changing the window procedure as below:

    LRESULT CALLBACK WindowProc(_In_ HWND hwnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam) {
    
        switch (uMsg)
        {
            case WM_CLOSE:
                DestroyWindow(hwnd);
                break;
    
            /*FOLLOWING LINES WERE REMOVED:
            case WM_DESTROY:
                PostQuitMessage(0);
                break;*/
    
            default: return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        return 0;
    }
    

    The problem occurred because I forgot that Windows Script Host isn't act as a standard WinForms application, so it doesn't need to be closed when window gets destroyed.