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 ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.