C # two methods to control the system volume/microphone size
Scenario: when playing a video device, you need to control the volume. The following methods can meet your requirements:
Method 1: Change the system volume settings
[DllImport ("user32.dll")] static extern void keybd_event (byte bVk, byte bScan, UInt32 dwFlags, UInt32 dwExtraInfo); [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 ;////// Increase the system volume ///Public void VolumeUp () {keybd_event (VK_VOLUME_UP, MapVirtualKey (VK_VOLUME_UP, 0), volume, 0); keybd_event (volume, MapVirtualKey (VK_VOLUME_UP, 0), Volume | KEYEVENTF_KEYUP, 0 );}////// Change the system volume and reduce the volume ///Public void VolumeDown () {keybd_event (VK_VOLUME_DOWN, MapVirtualKey (VK_VOLUME_DOWN, 0), success, 0); keybd_event (success, MapVirtualKey (VK_VOLUME_DOWN, 0), success | KEYEVENTF_KEYUP, 0 );}////// Change the system volume, mute ///Public void Mute () {keybd_event (keys, MapVirtualKey (keys, 0), KEYEVENTF_EXTENDEDKEY, 0); keybd_event (keys, MapVirtualKey (keys, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0 );}
Method 2: Change the program volume without changing 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 ;////// Volume control, but does not change the system volume settings ///Public int VolumeSize {get {return volumeSize;} set {volumeSize = value ;}} public void SetCurrentVolume () {if (volumeSize <0) {volumeSize = 0 ;} if (volumeSize> 100) {volumeSize = 100;} System. UInt32 Value = (System. UInt32) (double) 0 xffff * (double) volumeSize/(double) (volumeMaxScope-v olumeMinScope); // map the value of trackbar to 0x0000 ~ 0xFFFF range // limits the value range. if (Value <0) {Value = 0;} if (Value> 0 xffff) {Value = 0 xffff;} System. UInt32 left = (System. UInt32) Value; // left-channel volume System. UInt32 right = (System. UInt32) Value; // right waveOutSetVolume (0, left <16 | right); // "<" left shift, "|" logical or operation}