Intercept WM_CLOSE for cleanup operations

醉酒当歌 提交于 2019-12-02 02:16:25

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

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!