0

I wanted to know if any application in the foreground(except this application) is closed by clicking the cross button on the top-right or any other way like Ctrl + f4. Here is what I have created so far:

  1. create window event
void CALLBACK WinEventProc( 
    HWINEVENTHOOK hWinEventHook,
    DWORD         event,
    HWND          hwnd,
    LONG          idObject,
    LONG          idChild,
    DWORD         dwEventThread,
    DWORD         dwmsEventTime 
) {
    handleProcess(hwnd);
    // handleProcess does other operations
}
  1. Call the window event in wWinMain()
...
winDestructionHook = SetWinEventHook(EVENT_OBJECT_DESTROY, EVENT_OBJECT_DESTROY,
                     NULL, WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT);
...

The problem here is the window event is triggered without any window-closed action, but I wanted to activate it only on application closed.

Adam
  • 23
  • 4
  • Perhaps a silly question. If you want to know when the window is being destroyed, why not just wait on [WM_DESTROY](https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-destroy)? – WhozCraig Aug 25 '21 at 05:42
  • "*I wanted to activate it only on application closed*" - There is no WinEvent notification for that specific task. Consider using `SetWindowsHookEx()` instead, handling `WH_CALLWNDPROC` events looking for `WM_CLOSE` or `WM_SYSCOMMAND(SC_CLOSE)` messages, handling `WH_GETMESSAGE` events looking for `WM_QUIT` messages, etc. – Remy Lebeau Aug 25 '21 at 05:46
  • @RemyLebeau Actually, I need to track other foreground apps in case they are closed by user. Can you elaborate more on your comment above. – Adam Aug 25 '21 at 09:41
  • @WhozCraig, Sorry but I need to watch for other app running on the foreground instead the same app(monitor app). – Adam Aug 25 '21 at 09:42
  • @Adam in that case, I would propably use `SetWinEventHook()` to detect foreground changes. Grab the new foreground HWND, get its process ID, open a handle to the process, and wait for it to be signaled, indicating the process terminated. If the foreground changes, stop monitoring the old process and start monitoring the new process. Repeat. – Remy Lebeau Aug 25 '21 at 14:22
  • @Adam there is a way to monitor process start/stop events on a lower level, but I don't have those details right now – Remy Lebeau Aug 25 '21 at 14:23
  • Call [GetWindowThreadProcessId](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowthreadprocessid), then [enumerate all threads](https://stackoverflow.com/a/1206915/1889329), and finally call [EnumThreadWindows](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumthreadwindows) to see if the process has any other windows. This is littered with race conditions. A more robust solution would rather listen for process termination. – IInspectable Aug 25 '21 at 19:26

0 Answers0