Kalos92
Kalos92

Reputation: 69

Checking if another window is closed c++

I'm developing an application that checks open windows on a user computer on Windows (just like the Task Manager)

I used EnumWindows to list all the active window and it works, now i want to create a function that write a message on the console when a windows has been closed. Is possible or i have to check an array of WindowHandler in a separate thread and how do I check their status?

Thank for the help.

Upvotes: 3

Views: 1490

Answers (1)

IInspectable
IInspectable

Reputation: 51503

The easiest solution is to use WinEvents, by registering for EVENT_OBJECT_DESTROY events. The code is fairly straight forward:

#include <windows.h>

namespace {
    HWINEVENTHOOK g_WindowDestructionHook = NULL;
}

inline void CALLBACK WinEventProc( HWINEVENTHOOK hWinEventHook,
                                   DWORD         event,
                                   HWND          hwnd,
                                   LONG          idObject,
                                   LONG          idChild,
                                   DWORD         dwEventThread,
                                   DWORD         dwmsEventTime ) {
    // Filter interesting events only:
    if ( idObject == OBJID_WINDOW && idChild == CHILDID_SELF ) {
        wprintf( L"Window destroyed: HWND = %08X\n", hwnd );
    }
}

inline void RegisterWindowDestructionHook() {
    g_WindowDestructionHook = ::SetWinEventHook( EVENT_OBJECT_DESTROY,
                                                 EVENT_OBJECT_DESTROY,
                                                 NULL,
                                                 WinEventProc,
                                                 0, 0,
                                                 WINEVENT_OUTOFCONTEXT );
}

inline void UnregisterHook() {
    ::UnhookWinEvent( g_WindowDestructionHook );
}

Using this is equally simple:

::CoInitialize( NULL );
RegisterWindowDestructionHook();

MSG msg = {};
while ( ::GetMessageW( &msg, nullptr, 0, 0 ) > 0 ) {
    ::TranslateMessage( &msg );
    ::DispatchMessageW( &msg );
}

UnregisterHook();
::CoUninitialize();

Upvotes: 2

Related Questions