有人知道如何使用C#编程来静音Windows XP的音量吗?
声明此内容以进行P/Invoke:
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);
然后使用这行代码来静音/取消静音声音。
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);
public static void ToggleMute(IntPtr handle)
{
SendMessageW(handle, WM_APPCOMMAND, handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
}
在WPF窗口中:
VolumeXP.ToggleMute(new WindowInteropHelper(this).Handle);
- Stephen Kennedy0x80000
?APPCOMMAND_VOLUME_MUTE
被定义为 8
,但是当我使用 8
时它会失败,但是当我使用你的 0x80000
时它可以工作。这很奇怪。 - Noitidarttry
{
//Instantiate an Enumerator to find audio devices
NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator();
//Get all the devices, no matter what condition or status
NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All);
//Loop through all devices
foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol)
{
try
{
//Show us the human understandable name of the device
System.Diagnostics.Debug.Print(dev.FriendlyName);
//Mute it
dev.AudioEndpointVolume.Mute = true;
}
catch (Exception ex)
{
//Do something with exception when an audio endpoint could not be muted
}
}
}
catch (Exception ex)
{
//When something happend that prevent us to iterate through the devices
}
void SetPlayerMute(int playerMixerNo, bool value)
{
Mixer mx = new Mixer();
mx.MixerNo = playerMixerNo;
DestinationLine dl = mx.GetDestination(Mixer.Playback);
if (dl != null)
{
foreach (MixerControl ctrl in dl.Controls)
{
if (ctrl is MixerMuteControl)
{
((MixerMuteControl)ctrl).Value = (value) ? 1 : 0;
break;
}
}
}
}
这是Mike de Klerks答案的稍微改进版本,不需要“on error resume next”代码。
步骤1:将NAudio NuGet包添加到您的项目中(https://www.nuget.org/packages/NAudio/)
步骤2:使用以下代码:
using (var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator())
{
foreach (var device in enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.Render, NAudio.CoreAudioApi.DeviceState.Active))
{
if (device.AudioEndpointVolume?.HardwareSupport.HasFlag(NAudio.CoreAudioApi.EEndpointHardwareSupport.Mute) == true)
{
Console.WriteLine(device.FriendlyName);
device.AudioEndpointVolume.Mute = false;
}
}
}
CoreAudioDevice defaultPlaybackDevice = new
CoreAudioController().DefaultPlaybackDevice;
if (!defaultPlaybackDevice.IsMuted)
defaultPlaybackDevice.ToggleMute();