2009-06-12 62 views
7

我正在做一个应用程序,用于在用户注销时清除临时文件,历史记录等。那么如何知道系统是否要注销(使用C#)?从系统获取注销事件

回答

9

有一个在环境类讲述如果关机过程已经开始了物业:

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 
    } 
    } 

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

+0

但请记住,在Vista +你很少有时间关闭期间做的东西,所以请确保您不能阻止或等待任何原因(即试图删除可能位于网络共享中的文件等) – 2009-06-12 21:34:08

0

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

6

如果你特别需要注销的情况下,您可以修改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 
    } 
}