Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if another window is closed c++

Tags:

c++

winapi

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.

like image 660
Kalos92 Avatar asked Aug 06 '26 10:08

Kalos92


1 Answers

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();
like image 78
IInspectable Avatar answered Aug 09 '26 01:08

IInspectable