Friday, June 08, 2007

Fast User Switching, Vista Compliance, and .Net

I recently got involved in some work to make a .Net application comply with the Vista certification rules. When it came time to work on support for Fast User Switching, I was surprised to discover that Vista does not isolate sound to the active session, and that Vista Certification requires that your application stop playing sounds while its Windows session is not the active session.

After some searching, I discovered that .Net 2.0 introduced this handy event: Microsoft.Win32.SystemEvents.SessionSwitch. When this event fires, you get a SessionSwitchEventArgs object, which (by way of its Reason property) tells you what caused the event to fire. From my testing, Fast User Switching results only in SessionSwitch events fired for the following reasons: SessionSwitchReason.ConsoleDisconnect and SessionSwitchReason.ConsoleConnect. By hooking onto this event and keeping track of session state, you can correctly determine whether it's okay to play a sound.

Note that SystemEvents.SessionSwitch is a static event. If you do not explicitly detach from the event when you are done with it, as in a Dispose method, you will introduce a memory leak.