public class demo
{
//運用WinAPI控制電腦靜音與音量
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;
//private static IntPtr Handle;
public static Process p = Process.GetCurrentProcess();
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
public static void btnVup_Click()
{
// 聲音變大
SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_UP);
}
public static void btnVdown_Click()
{
// 聲音變小
SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_DOWN);
}
public static void btnMute_Click()
{
// 靜音
SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
}
/**
* xp以下的電腦適用
* */
[DllImport("winmm.dll")]
public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
[DllImport("winmm.dll")]
public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
public static void vol_up()
{
// 設定變數CurrVol用以取得目前音量
uint CurrVol = 0;
// 透過waveOutGetVolume取得目前音量給變數CurrVol
waveOutGetVolume(IntPtr.Zero, out CurrVol);
// 計算音量大小
ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
// 將音量大小分為10階
int vol_value = CalcVol / (ushort.MaxValue / 10);
Console.WriteLine(CalcVol / (ushort.MaxValue / 10));
// 音量值加 1
vol_value = vol_value + 1;
ValueChanged(vol_value);
}
public static void vol_down()
{
// 設定變數CurrVol用以取得目前音量
uint CurrVol = 0;
// 透過waveOutGetVolume取得目前音量給變數CurrVol
waveOutGetVolume(IntPtr.Zero, out CurrVol);
// 計算音量大小
ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
// 將音量大小分為10階
int vol_value = CalcVol / (ushort.MaxValue / 10);
Console.WriteLine(CalcVol / (ushort.MaxValue / 10));
// 音量值減 1
vol_value = vol_value - 1;
ValueChanged(vol_value);
}
// 值改變時,設定音量
private static void ValueChanged(int value)
{
// 計算要設定的音量大小
int NewVolume = ((ushort.MaxValue / 10) * value);
// 設定相同的數值於左聲道與右聲道
uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
// 設定音量
waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
}
}
留言
張貼留言