19.1. Dealing with Operating System Shutdown, Power Management, or User Session Changes
Problem
You want to be notified whenever the operating system or a user has initiated an action that requires your application to shut down or be inactive (user logoff, remote session disconnect, system shutdown, hibernate/restore, etc.). This notification will allow you have your application respond gracefully to the changes.
Solution
Use the Microsoft.Win32.SystemEvents class to get notification of operating system, user session change, and power management events. The RegisterForSystemEvents method shown next hooks up the five event handlers necessary to capture these events and would be placed in the initialization section for your code:
public static void RegisterForSystemEvents( )
{
// Always get the final notification when the event thread is shutting down
// so we can unregister.
SystemEvents.EventsThread Shutdown +=
new EventHandler(OnEventsThread Shutdown);
SystemEvents.PowerModeChanged +=
new PowerModeChangedEventHandler(OnPowerModeChanged);
SystemEvents.SessionSwitch +=
new SessionSwitchEventHandler(OnSessionSwitch);
SystemEvents.SessionEnding +=
new SessionEndingEventHandler(OnSessionEnding);
SystemEvents.SessionEnded +=
new SessionEndedEventHandler(OnSessionEnded);
}The EventsThreadShutdown event notifies you of when the thread that is distributing the events from the SystemEvents class is shutting down so that you can unregister the events on the SystemEvents class if you have not ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access