Introduction
I was recently working on the Windows API and thought of creating a small application that can increase, decrease and mute the volume in .NET. Since we will be consuming unmanaged DLL functions, hence I will be using P/Invoke that enables managed code to call unmanaged functions implemented in DLL’s, like the ones in the Win32 API. For this purpose, we will be using the
System.Runtime.InteropServices namespace
In this article, I assume you are familiar with interoperating with Unmanaged Code. If you have never worked with unmanaged code, please read the MSDN article
Interoperating with Unmanaged Code.
I have created a Windows Application and added three Button Controls to the form as shown below:
The Code
Let us see the code that will be invoked on every button click:
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int APPCOMMAND_VOLUME_UP = 0xA0000;
private const int APPCOMMAND_VOLUME_DOWN = 0x90000;
private const int WM_APPCOMMAND = 0x319;
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg,
IntPtr wParam, IntPtr lParam);
Mute / Unmute
if (checkMute)
{
this.btnMute.Text = "Unmute Volume";
this.btnMute.ForeColor = System.Drawing.Color.Red;
checkMute = false;
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_MUTE);
}
else
{
this.btnMute.Text = "Mute Volume";
this.btnMute.ForeColor = System.Drawing.Color.Black;
checkMute = true;
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_MUTE);
}
Decrease
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_DOWN);
Increase
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle,
(IntPtr)APPCOMMAND_VOLUME_UP);
As seen in the code above, we are first using the DllImportAttribute attribute that provides the information needed to call a function exported from an unmanaged DLL. On each button click, we are using the
SendMessageW() function to send the specified message to a window to increase, decrease and mute the volume.
I hope you liked the article and I thank you for viewing it.
,
This attachment is hidden for guests. Please log in or register to see it.