方法一:比较简单的办法是通过SendMessage发送WM_APPCOMMAND消息来实现(类似于实体键盘上的音量键操作),SendMessage原型如下:
LRESULT SendMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM IParam)
第一个参数hWnd为消息接收窗口句柄,一般设置自己的应用程序窗体句柄(也可以设置为其它程序的窗体句柄,说白了就是模拟键盘上的音量键,不管哪个窗口接收都是一样的效果);
第二个参数Msg为消息类型,这里设置为:WM_APPCOMMAND;
第三个参数wParam在这里表示消息来源,一般同hWnd,也可以是hWnd的子控件句柄(经测试直接设为0或其它值也不受影响);
第四个参数lParam在这里表示消息的具体操作,音量调节可选下面参数
APPCOMMAND_VOLUME_MUTE 静音状态切换
APPCOMMAND_VOLUME_UP 调高音量
APPCOMMAND_VOLUME_DOWN 降低音量
C#.NET代码示例:
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, int lParam);
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;//C++头文件中原始值为0x8,使用时设置为APPCOMMAND_VOLUME_MUTE * 0x10000
private const int APPCOMMAND_VOLUME_UP = 0xA0000;//C++头文件中原始值为0xA,在使用时设置为APPCOMMAND_VOLUME_UP * 0x10000
private const int APPCOMMAND_VOLUME_DOWN = 0x90000;//C++头文件中原始值为0x9,在使用时设置为APPCOMMAND_VOLUME_DOWN * 0x10000
private const int WM_APPCOMMAND = 0x319;
private void VolumeUp()
{
SendMessage(this.Handle, WM_APPCOMMAND, this.Handle, APPCOMMAND_VOLUME_UP);
}
private void VolumeDown()
{
SendMessage(this.Handle, WM_APPCOMMAND, this.Handle, APPCOMMAND_VOLUME_DOWN);
}
private void MuteChange()
{
SendMessage(this.Handle, WM_APPCOMMAND, this.Handle, APPCOMMAND_VOLUME_MUTE);
}
方法二:通过调用CoreAudioApi来实现,经测试比较好用。C#.NET代码示例如下:
private void test()
{
string str = "";
CoreAudioApi.MMDeviceEnumerator mMDeviceEnumerator = new CoreAudioApi.MMDeviceEnumerator();
CoreAudioApi.MMDeviceCollection speakDevices = mMDeviceEnumerator.EnumerateAudioEndPoints(CoreAudioApi.EDataFlow.eRender, CoreAudioApi.EDeviceState.DEVICE_STATE_ACTIVE);
if (speakDevices.Count > 0)
{
CoreAudioApi.MMDevice mMDevice = speakDevices[0];
//mMDevice.AudioEndpointVolume.MasterVolumeLevelScalar = 0.02f;
mMDevice.AudioEndpointVolume.MasterVolumeLevelScalar = 20f / 100;//设置音量为20%
str = string.Format("设备名称:{0} - [ID:{1}]\r\n", mMDevice.FriendlyName,mMDevice.ID);
str = str + string.Format("通道数:{0}\r\n", mMDevice.AudioEndpointVolume.Channels.Count);
str = str + string.Format("当前静音状态:{0}\r\n", mMDevice.AudioEndpointVolume.Mute);
str = str + string.Format("当前音量格数:{0}\r\n", mMDevice.AudioEndpointVolume.StepInformation.Step);
str = str + string.Format("音量最小值:{0}\r\n", mMDevice.AudioEndpointVolume.VolumeRange.MindB);
str = str + string.Format("音量最大值:{0}\r\n", mMDevice.AudioEndpointVolume.VolumeRange.MaxdB);
str = str + string.Format("当前音量值:{0}\r\n", mMDevice.AudioEndpointVolume.MasterVolumeLevel);
str = str + string.Format("当前音量值百分比表示:{0}", mMDevice.AudioEndpointVolume.MasterVolumeLevelScalar*100);
mMDevice.AudioEndpointVolume.VolumeStepDown();//下调一格音量
mMDevice.AudioEndpointVolume.Mute = true;//设置为静音
mMDevice.AudioEndpointVolume.VolumeStepUp();//上调一格音量
}
//CoreAudioApi.MMDevice mMDevice = mMDeviceEnumerator.GetDefaultAudioEndpoint(CoreAudioApi.EDataFlow.eRender, CoreAudioApi.ERole.eMultimedia);
MessageBox.Show(str);
}