从系统获取注销事件

我正在做一个应用程序,用于在用户注销时清除Temp文件,历史记录等。 那我怎么知道系统是否要注销(在C#中)?

Environment类中有一个属性,它告诉关闭进程是否已经启动:

Environment.HasShutDownStarted 

但经过一些谷歌搜索,我发现这可能对你有所帮助:

  using Microsoft.Win32; //during init of your application bind to this event SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding); void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) { if (Environment.HasShutdownStarted) { //Tackle Shutdown } else { //Tackle log off } } 

但是,如果您只想清除临时文件,那么我认为区分关闭或注销对您没有任何影响。

如果您特别需要注销事件,则可以修改TheVillageIdiot答案中提供的代码,如下所示:

 using Microsoft.Win32; //during init of your application bind to this event SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding); void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) { if (e.Reason == SessionEndReasons.Logoff) { // insert your code here } } 

您可以使用WMI并观察Win32_ComputerShutdownEvent,其中Type等于0.您可以在此处找到有关此事件的更多信息,以及有关在.NET中使用WMI的更多信息。