Introduction
This small utility mutes the system volume each time you lock down your system. When you unlock your system, the volume is un-muted back. This utility uses the SessionSwitch
event from the Win32 namespace. With this event, we can catch the session switch for the lock down and unlock events. Using user32.dll with the SendMessageW
method, we can send the mute message to the system.
Background
In my company, we need to lock our system each time we move away from the computer. The volume of my speakers is a bit high, and my room partner complaints that he wants his quiet time whenever I leave the room. With this small utility, my system volume is mute every time I lock my computer.
Using the Code
Here is the declaration of the consts and the DllImport of user32.dll:
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int WM_APPCOMMAND = 0x319;
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg,
IntPtr wParam, IntPtr lParam);
We need to register to the SessionSwitch
event, so first we need to add a reference to the Win32 namespace. Just add a using
statement for Microsoft.Win32
. Now add the following to register to the event:
SystemEvents.SessionSwitch +=
new SessionSwitchEventHandler(this.SystemEvents_SessionSwitch);
Now, for the main event of this sample:
private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_MUTE);
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_MUTE);
}
}
You must detach the SessionSwitch
event when your application closes to avoid memory leaks.
SystemEvents.SessionSwitch -= new SessionSwitchEventHandler
(this.SystemEvents_SessionSwitch);
Points of Interest
It is always nice to learn about the events of the Operating System.
History
- 13th October, 2009: Initial post.