如何以编程方式设置系统音量?

如何使用C#应用程序更改Windows系统音量?

这里是代码:

using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Test { public class Test { 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); private void Mute() { SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE); } private void VolDown() { SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_DOWN); } private void VolUp() { SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_UP); } } } 

派生自: dotnetcurry

当使用WPF时,您需要使用new WindowInteropHelper(this).Handle来代替this.Handle (感谢Alex Beals)

我晚了一点,但如果你现在看有一个nuget包可用(AudioSwitcher.AudioApi.CoreAudio),简化了audio交互。 安装它然后就像这样简单:

 CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice; Debug.WriteLine("Current Volume:" + defaultPlaybackDevice.Volume); defaultPlaybackDevice.Volume = 80; 

如果其他答案中提供的教程过于复杂,则可以使用keybd_event函数尝试执行此类实现

 [DllImport("user32.dll")] static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo); 

用法:

 keybd_event((byte)Keys.VolumeUp, 0, 0, 0); // increase volume keybd_event((byte)Keys.VolumeDown, 0, 0, 0); // decrease volume 

如果您希望使用Core Audio API将其设置为精确值:

 using CoreAudioApi; public class SystemVolumeConfigurator { private readonly MMDeviceEnumerator _deviceEnumerator = new MMDeviceEnumerator(); private readonly MMDevice _playbackDevice; public SystemVolumeConfigurator() { _playbackDevice = _deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia); } public int GetVolume() { return (int)(_playbackDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100); } public void SetVolume(int volumeLevel) { if (volumeLevel < 0 || volumeLevel > 100) throw new ArgumentException("Volume must be between 0 and 100!"); _playbackDevice.AudioEndpointVolume.MasterVolumeLevelScalar = volumeLevel / 100.0f; } }