问题
Context:
I'm developing a screensaver in C# with VS2010 .NET 4.0 on Windows 8.1. It's quite "busy", accessing a database on initial load and doing some image processing before displaying to multi-monitors.
Issue:
In most cases the process shuts down cleanly either a) on mouse/keyboard movement in /s mode or when desk.cpl is closed in /p mode. A problem arises thought when I run in /p mode (desk.cpl open) and then I instigate either "settings" (/c mode) or "Preview" (/s mode). Once these new processes are closed the /p mode returns as you would expect but when desk.cpl is closed the /p mode process continues to run. This is intermittent however - sometimes it closes, sometimes it doesn't.
In /p mode I explicitly don't close the form on mouse movement etc as this is not appropriate for the desk.cpl preview window. My assumption therefore is that desk.cpl would kill my process but this doesn't seem to be happening consistently.
Question:
How can I ensure that /p mode will close down consistently?
回答1:
Two methods. You can either monitor the message pump for WM_DESTROY and close down on that, or you can set a timer and monitor to see if you have a visible window any more. Note that when the control panel replaces you (closes itself, or user chooses a new screen saver), your window is hidden, and I believe destroyed. Since you are Screen Saver, it seems less risky to possibly abort early than to hang on forever.
So set a non-Form Timer (Form timers may get destroyed if your window is being destroyed), and check yourself periodically. You can also, as somebody points out in the comments to your question, monitor GetParent, to see if it changes.
来源:https://stackoverflow.com/questions/21967757/screensaver-in-p-preview-mode-keeps-running-after-desk-cpl-is-closed