简体   繁体   中英

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

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 .

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.

您总是可以添加一个最小化的虚拟表单,该表单以最小化方式打开,任务栏上没有图标-不会产生任何视觉影响,但是会发送给表单关闭事件-您可以在其中记录关闭事件,并大概关闭/停止应用程序正在执行的其他操作。

处理Microsoft.Win32.SystemEvents.SessionEnding事件,并使用System.Environment.HasShutdownStarted检查它是否真正关闭

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