Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Log off event from system

Tags:

c#

.net

wpf

logout

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

like image 524
Sauron Avatar asked Jun 12 '09 03:06

Sauron


People also ask

How do I capture the system event log?

Click "Control Panel" > "System and Security" > "Administrative Tools", and then double-click "Event Viewer" Click to expand "Windows Logs" in the left pane, and then select "Application". Click the "Action" menu and select "Save All Events As".

How do I view the event log in CMD?

Start Windows Event Viewer through the command line As a shortcut you can press the Windows key + R to open a run window, type cmd to open a, command prompt window. Type eventvwr and click enter.

How do I find last logoff time?

Click on the 'Reports' tab and then select 'Local logon-Logoff'. Here, there are multiple reports that give you the logon information you need and more. Logon activity shows the logon attempts, with the username, logon time, name of the workstation, type of logon among other examples.

How do I view event logs on a remote computer?

Point to Administrative Tools, and then click Event Viewer. Right-click Event Viewer (top level). Select Connect to another computer. Type the computer name on which to view Event Logs, and click OK.


2 Answers

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.

like image 103
TheVillageIdiot Avatar answered Oct 16 '22 07:10

TheVillageIdiot


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
    }
}
like image 34
bjh Avatar answered Oct 16 '22 09:10

bjh