Scenario: You need to control the volume when doing the playback device, the following methods will meet your requirements
Method One: Change the system volume settings
[DllImport ("User32.dll")] static extern void keybd_event (byte bvk, byte Bscan, UInt32 dwFlags, UInt32 dwext Rainfo); [DllImport ("User32.dll")] static extern Byte Mapvirtualkey (UInt32 uCode, UInt32 umaptype); Private Const byte Vk_volume_mute = 0xAD; Private Const byte Vk_volume_down = 0xAE; Private Const byte VK_VOLUME_UP = 0xAF; Private Const UInt32 Keyeventf_extendedkey = 0x0001; Private Const UInt32 KEYEVENTF_KEYUP = 0x0002; <summary>//Change system volume size, increase///</summary> public void Volumeup () {k Eybd_event (Vk_volume_up, Mapvirtualkey (vk_volume_up, 0), Keyeventf_extendedkey, 0); Keybd_event (Vk_volume_up, Mapvirtualkey (vk_volume_up, 0), Keyeventf_extendedkey | Keyeventf_keyup, 0); }///<summary>//Change the system volume size to decrease///</summary> public void Volumedown () { Keybd_event (Vk_volume_down, MapvirtualkEY (vk_volume_down, 0), Keyeventf_extendedkey, 0); Keybd_event (Vk_volume_down, Mapvirtualkey (vk_volume_down, 0), Keyeventf_extendedkey | Keyeventf_keyup, 0); }///<summary>//Change the system volume, mute///</summary> public void Mute () { Keybd_event (Vk_volume_mute, Mapvirtualkey (vk_volume_mute, 0), Keyeventf_extendedkey, 0); Keybd_event (Vk_volume_mute, Mapvirtualkey (vk_volume_mute, 0), Keyeventf_extendedkey | Keyeventf_keyup, 0); }
Method Two: Change the program volume, but do not change the system volume settings
[DllImport ("Winmm.dll")] private static extern int Waveoutsetvolume (int hwo, System.UInt32 pdwvolume); [DllImport ("Winmm.dll")] private static extern uint Waveoutgetvolume (int hwo, out System.UInt32 pdwvolume); #region private int volumeminscope = 0; private int volumemaxscope = 100; private int volumesize = 100; <summary>///volume control, but do not change system volume settings///</summary> public int Volumesize { get {return volumesize;} set {volumesize = value;} } public void Setcurrentvolume () {if (Volumesize < 0) {Volumesize = 0; } if (Volumesize >) {volumesize = 100; } system.uint32 Value = (system.uint32) (double) 0xFFFF * (double) volumesize/(double) (volumemaxscope-v Olumeminscope)), or//the value of TrackBar is first mappedShot to 0X0000~0XFFFF range//Limit value range if (value < 0) {value = 0; } if (Value > 0xFFFF) {value = 0xFFFF; } System.UInt32 left = (system.uint32) value;//The right-hand channel volume System.UInt32 r = (system.uint32) value;// Waveoutsetvolume (0, left << | right); "<<" shift Left, "|" Logical OR Operation}
C # Two ways to control the volume/microphone size of the system