使用C#静音Windows卷

jin*_*ngy 17 c# audio volume winforms

任何人都知道如何使用C#以编程方式静音Windows XP卷?

Jor*_*ira 12

为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);
Run Code Online (Sandbox Code Playgroud)

然后使用此线来静音/取消静音.

SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,在 XP 中工作得很好。不过我使用的是 WPF,所以没有 this.Handle。相反:`public static void ToggleMute(IntPtr handle) { SendMessageW(handle, WM_APPCOMMAND, handle, (IntPtr)APPCOMMAND_VOLUME_MUTE); }` 在 WPF 窗口中:`VolumeXP.ToggleMute(new WindowInteropHelper(this).Handle);` (2认同)

Mik*_*erk 5

你可以在 Windows Vista/7 和 8 上使用什么:

您可以使用NAudio
下载最新版本。提取 DLL 并在 C# 项目中引用 DLL NAudio。

然后添加以下代码以遍历所有可用的音频设备并尽可能将其静音。

try
{
    //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
}
Run Code Online (Sandbox Code Playgroud)