Getting a formless C# program to close itself during shutdown/restart?

非 Y 不嫁゛ 提交于 2019-12-13 00:23:12

问题


I'm writing a program which creates no forms at all until one is required. The problem is, it's preventing shutdown from continuing automatically. I've seen discussions about adding an if to form closing events to check if it's due to shutdown, but as I've said, my program is meant to have no forms at all until required.

Is there any event or some other method that will allow me to know when my program should be closing itself to allow for Windows to shut itself down automatically? And it's not multithreaded.


回答1:


You can use the SystemEvents class, to "listen to" users logging out, or shutting down.

If I understand the documentation correctly (and a deep study with Reflector confirms this):

  • The systemevents will spawn a new thread that receives the messages from windows (it has its own messagepump).
  • When an event is received, your code will be called, from the new thread. You should be aware of this.



回答2:


You could always add a dummy form which you open minimized, with no icon on the taskbar - it won't have any visual impact, but will be sent the form closing event - where you could note the shutdown event, and presumably shut down/stop whatever else there is that your application is doing.




回答3:


Handling the Microsoft.Win32.SystemEvents.SessionEnding event, and checking if it's an actual shutdown with System.Environment.HasShutdownStarted



来源:https://stackoverflow.com/questions/3733462/getting-a-formless-c-sharp-program-to-close-itself-during-shutdown-restart

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