Get Log off event from system

2020-03-02 03:17发布

I am doing an application which is used to clear the Temp files, history etc, when the user log off. So how can I know if the system is going to logoff (in C#)?

标签: c# .net wpf logout
4条回答
我想做一个坏孩纸
2楼-- · 2020-03-02 03:27

If you have a Windows Form, you can handle the FormClosing event, then check the e.CloseReason enum value to determine if it equals to CloseReason.WindowsShutDown.

private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        // Your code here
    }
}
查看更多
Rolldiameter
3楼-- · 2020-03-02 03:31

There is a property in Environment class that tells about if shutdown process has started:

Environment.HasShutDownStarted

But after some googling I found out that this may be of help to you:

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

But if you only want to clear temp file then I think distinguishing between shutdown or log off is not of any consequence to you.

查看更多
劫难
4楼-- · 2020-03-02 03:42

You can use WMI and watch the Win32_ComputerShutdownEvent where Type is equal to 0. You can find more information about this event here, and more about using WMI in .NET here.

查看更多
▲ chillily
5楼-- · 2020-03-02 03:52

If you specifically need the log-off event, you can modify the code provided in TheVillageIdiot's answer as follows:

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
    }
}
查看更多
登录 后发表回答