Get Log off event from system

Sauron picture Sauron · Jun 12, 2009 · Viewed 10.8k times · Source

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#)?

Answer

TheVillageIdiot picture TheVillageIdiot · Jun 12, 2009

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.