C # often needs to control the volume of the system in developing Windows applications, in two ways:
1. Use Win API control
2. Using C + + DLL control
Win API Control:
The system volume can be controlled using both user32.dll and Winmm.dll, and the difference is the version of the win system. Winmm.dll XP environment available, User32.dll Vista and above version.
C + + DLL control:
Coreaudioapi is the third party in C + + encapsulates the volume control, download the DLL on the Internet and then reference in the project can be used. Coreaudioapi Vista and above version support.
The following code
1.WINMM control mode, involving the XP system waveform sound of the left and right channel, high for the left-hand channel, low for the right-hand channel:
Copy Code code 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) & 0xFFFF;
UINT Vall = v | (v << 16);
int retVal = Waveoutsetvolume (IntPtr.Zero, Vall);
}
2.user32 control mode:
Copy Code code 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 Code code as follows:
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 ();