C # You often need to control the volume of the system when developing a Windows application. There are two methods:
1. Use Win Api Control
2. Use C ++ dll for control
Win Api control:
You can use both user32.dll and winmm. dll to control the system volume. The difference is the Windows system version. Available in winmm. dll Xp environment, user32.dll Vista and later versions.
C ++ dll Control:
CoreAudioApi is a third-party C ++ package for volume control. You can use CoreAudioApi by downloading DLL from the Internet and referencing it in the project. CoreAudioApi Vista and later versions are supported.
The following code is provided:
1. winmm control mode, involving the Left and Right audio channels of the waveform sound of the XP system. The high is the left audio channel, and the low is the right audio channel:
Copy codeThe Code is as follows: 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) & 0 xffff;
Uint vAll = v | (v <16 );
Int retVal = WaveOutSetVolume (IntPtr. Zero, vAll );
}
2. user32 Control Mode:
Copy codeThe Code is as follows: 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
Copy codeThe Code is as follows: CoreAudioApi
Using CoreAudioApi;
Public void SetVol (double arg ){
Device = DevEnum. getdefadefaaudioendpoint (EDataFlow. eRender, ERole. eMultimedia );
Device. AudioEndpointVolume. MasterVolumeLevelScalar = (float) arg;
}
Private MMDevice device;
Private MMDeviceEnumerator DevEnum = new MMDeviceEnumerator ();