C# Windows Form Killed By Task Manager…Is There a Way to Run Shutdown Function?

别说谁变了你拦得住时间么 提交于 2020-01-10 05:50:11

问题


I doubt this is even possible. So your app is running and user decides to End Process via Task Manager. Is there a method/action to save data during process.kill? I doubt there is but I had to ask.

Also, if a user shuts down/restarts PC (as in windows update/manual restart), what action would the app execute? Window_Unloaded? On this second question, I would like to find a way to ensure my app does not show up as a 'if you want to restart, kill this app' situation and want to save needed data.

Your two cents is greatly appreciated!


回答1:


It's not possible to do what you want unless you have two processes; one monitoring the other one's status and do some stuff upon its termination. The watchdog process might be a Windows Service Application without GUI.

Windows sends a quit message to every opened application when normal shutdown occurs. You can run some code (usually housekeeping stuff) upon receiving the message and exit the application. It shouldn't take long or Windows will automatically ask user if they want to kill the application.

Force shutdown kills all processes immediately (in no particular/predictable order). So you can't (easily) detect it.

I suggest you to save everything needed as soon as possible to prevent data loss when the application process gets killed.




回答2:


If something terminates your running app, then you don't get an opportunity to do anything, just die. You modify your app such that all data is always saved to some persistent location, so if the app dies, the persisted data remains. Obviously you have to design for this. Then if the user does a "save", you commit to the "real" datastore.

If Windows is going to reboot, it should send a message to your app, which you can handle. Not sure if this works for all GUI/console/service -type apps however.



来源:https://stackoverflow.com/questions/3326242/c-sharp-windows-form-killed-by-task-manager-is-there-a-way-to-run-shutdown-fun

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