Get Log off event from system

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.


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

Tags:

C#

.Net

Wpf

Logout