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
?
1234567891011121314151617181920212223242526272829303132333435363738 |
[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 ; /// <summary> /// Change the system volume and increase the volume /// </summary> public void VolumeUp() { keybd_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 and reduce the volume. /// </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 and mute it /// </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 2: Change the program volume without changing the system volume settings
?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
[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 without changing the system volume settings /// </summary> 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 ) 0xffff * ( double )volumeSize / ( double )(volumeMaxScope - v olumeMinScope)); // Map the value of trackbar to 0x0000 ~ 0xFFFF range // Limit the value range if (Value < 0 ) { Value = 0 ; } if (Value > 0xffff ) { Value = 0xffff ; } System.UInt32 left = (System.UInt32)Value; // Left audio volume System.UInt32 right = (System.UInt32)Value; // Right waveOutSetVolume( 0 , left << 16 | right); // "<" Left shift, "|" logical or operation } |