Intercept WM_CLOSE for cleanup operations

前端 未结 4 863
悲哀的现实
悲哀的现实 2021-01-22 06:58

I have an external application that calls my application and is supposed to end it when the job is done. The log from this external application claims it uses WM_CLOSE

相关标签:
4条回答
  • 2021-01-22 07:31

    You must create hidden window using winapi, and handle WM_CLOSE message in its message loop. Is your app using any gui elements?

    0 讨论(0)
  • 2021-01-22 07:33

    You could just handle WM_CLOSE in your message loop to do whatever cleanup is necessary, or even abort the close (by returning 1 instead of 0). See e.g. this: http://cboard.cprogramming.com/windows-programming/141438-handling-wm_close-wm_destroy.html#post1056273

    Edit: for console applications, this may be of interest: http://support.microsoft.com/kb/178893

    0 讨论(0)
  • 2021-01-22 07:36

    The official solution for console applications is HandlerRoutine, a callback set by SetConsoleCtrlHandler. Windows will call your handler with a CTRL_CLOSE_EVENT argument in case of a WM_CLOSE exit.

    When you're using a class method with SetConsoleCtrlHandler, it must be a static method - Windows won't provide you with a this pointer.

    0 讨论(0)
  • 2021-01-22 07:38

    The easiest way I think is to call PeekMessage from time to time.

    BOOL IsCloseEventReceived()
    {
        MSG msg;
        return PeekMessage(&msg, NULL, WM_CLOSE, WM_CLOSE, PM_NOREMOVE);
    }
    

    This function should work to check if a WM_CLOSE message has been posted. It's not blocking, and you'll need to call it on a regular basis.

    I might be wrong, but I think you don't need a hidden window to handle messages, a message queue is attached to your process the first time you call a messages-related function, like PeekMessage. However if you receive a WM_CLOSE message prior to your first call of this function it might be lost.

    0 讨论(0)
提交回复
热议问题