Intercept WM_CLOSE for cleanup operations

寵の児 提交于 2019-12-02 02:38:55

问题


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 on my app.

How can I intercept the WM_CLOSE message in my application to do some cleanup operations? I tried at_exit() and wrapping it in a class, but I think I have the wrong approach.


回答1:


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




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/8698881/intercept-wm-close-for-cleanup-operations

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