简体   繁体   中英

How to use WinAPI , prevent/cancel a window closing?

I want to prevent users from closing a window by Alt + F4 or by clicking the close button.

How to achieve this?

I guess the windows API can do it, but I don't have any experience, and I can't find a specific solution.

Of course, it's good to be able to implement it,don't have to use a specific API.


Background: it is very difficult to find the last place in Word after closing it for a few days. After word2013, word2013 brought with it a way to return to the previous reading position, but that thing is very unstable and often can't be saved. When word is closed, I want to stop closing and pop up a notice to remind me to add a bookmark before exiting.

EDIT: This won't work, as it turned out. At least the message hook won't work because the message is posted and not sent, and about the CBT hook I'm not sure either, and I can't test it at the moment to give an evidence-based statement. The solution is probably to subclass the window but this is also non-trivial and I can't explain it properly and with working examples right now. I can't delete this answer though because it already has a comment. See here for more info. So take it with a grain of salt. I'm turning the answer to community wiki, feel free to edit it and fix/improve the solution!

EDIT2: Seems even subclassing won't be enough because Word is doing things its own way.


You need a windows hook . Either a CBT hook or a getmessage hook will do.

You have to create a DLL for this to work. The hook handler must be located in the DLL. It must have the same bitness as Word (probably 64 Bit). Then you call SetWindowsHookEx to install a global hook.

In the hook, you will have to check whether the current action is a window-closing attempt (in a CBT hook you would check for a HCBT_SYSCOMMAND of SC_CLOSE , in a getmessage hook you would check for a WM_CLOSE message), and whether it is about a Word window (for example using the window class - not sure if it has a recognizable class, you'd have to check - or the process' executable file name which you can get using GetModuleFileName since you will run inside Word's process) and prevent the action (by returning 1 from a CBT hook or returning 0 from a getmessage hook - to allow , call CallNextHookEx ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM