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#)?
Asked
Active
Viewed 1.2k times
4 Answers
10
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.

TheVillageIdiot
- 40,053
- 20
- 133
- 188
-
Keep in mind though, on Vista+ you have very little time to do stuff during shutdown, so make sure that you can't block or wait for any reason (i.e. trying to delete a file that might be on a network share, etc...) – Ana Betts Jun 12 '09 at 21:34
-
thanks @Paul then should it be advisable to make an entry somewhere so that windows clear the stuff on next reboot or login? – TheVillageIdiot Jun 13 '09 at 02:42
-
what is SystemEvents ? – Kiquenet Apr 03 '19 at 19:34
-
Shutdown, log off...shutdown using Wake On LAN ? – Kiquenet Apr 03 '19 at 19:35
9
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
}
}
0
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
}
}

riofly
- 1,694
- 3
- 19
- 40
-
1
-
1@UweKeim the CloseReason enum do not consider "User log off" scenario. https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.closereason?view=windowsdesktop-7.0 – riofly Dec 09 '22 at 09:48