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#)?
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".
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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With