Using c-sharp to control the volume of Windows system

  • 2020-04-01 23:36:53
  • OfStack

C# developing Windows applications often requires controlling the volume of the system in two ways:

1. Use Win Api control

2. Use C++ DLL control

Win Api control:

User32. DLL and winmm. DLL can be used to control the system volume, the difference is the version of the Win system. Winmm.dll Xp environment available, user32. DLL Vista and above.

C++ DLL control:

CoreAudioApi is C++ third party package volume control, after downloading DLL on the Internet and then the project can be used. CoreAudioApi Vista and above supported.

Here's the code

1. Winmm control mode, involving the left and right sound channels of the waveform sound of Xp system, the high level is the left sound channel, the low level is the right sound channel:


winmm 
 [DllImport("winmm.dll", EntryPoint = "waveOutSetVolume")]
 public static extern int WaveOutSetVolume(IntPtr hwo, uint dwVolume);

 private void SetVol(double arg){
     double newVolume = ushort.MaxValue * arg / 10.0;

     uint v = ((uint)newVolume) & 0xffff;
     uint vAll = v | (v << 16);

     int retVal = WaveOutSetVolume(IntPtr.Zero, vAll);
 }

2. User32 control mode:

user32 
 [DllImport("user32.dll")]
 public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

 public void SetVol(){
     p = Process.GetCurrentProcess();
     for (int i = 0; i < 5; i++) {
     SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_UP);
     }
 }

 private Process p;
 private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
 private const int APPCOMMAND_VOLUME_UP = 0x0a0000;
 private const int APPCOMMAND_VOLUME_DOWN = 0x090000;
 private const int WM_APPCOMMAND = 0x319;

3. CoreAudioApi

CoreAudioApi 
 Using CoreAudioApi;

 public void SetVol(double arg) {
     device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
     device.AudioEndpointVolume.MasterVolumeLevelScalar = (float)arg;
 }

 private MMDevice device;
 private MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();


Related articles: