How to detect if the user is shutting down or logging off in WPF application?

Withing WPF application, you can detect if the user is shutting down or logging off and thereby take some action like saving for example your project. In order to do so, you will need to register to the Application SessionEnding event.


Application.Current.SessionEnding +=new SessionEndingCancelEventHandler(Current_SessionEnding);

You can then use the SessionEndingCancelEventArgs.ReasonSessionEnding to know exactly the reason of the session ending, whether it was because of a shuttdown or logoff.


private void Current_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
  if (e.ReasonSessionEnding == ReasonSessionEnding.Logoff)
      MessageBox.Show("User Logged off the computer");
  else if (e.ReasonSessionEnding == ReasonSessionEnding.Shutdown)
      MessageBox.Show("User Shut down his machine");
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: