C# 系統音量調整由程式控制

  1. public class demo
  2. {
  3. //運用WinAPI控制電腦靜音與音量
  4. private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
  5. private const int APPCOMMAND_VOLUME_UP = 0x0a0000;
  6. private const int APPCOMMAND_VOLUME_DOWN = 0x090000;
  7. private const int WM_APPCOMMAND = 0x319;
  8. //private static IntPtr Handle;
  9. public static Process p = Process.GetCurrentProcess();
  10.  
  11. [DllImport("user32.dll")]
  12. public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
  13.  
  14. public static void btnVup_Click()
  15. {
  16. // 聲音變大
  17. SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_UP);
  18. }
  19.  
  20. public static void btnVdown_Click()
  21. {
  22. // 聲音變小
  23. SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_DOWN);
  24. }
  25.  
  26. public static void btnMute_Click()
  27. {
  28. // 靜音
  29. SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
  30. }
  31.  
  32.  
  33. /**
  34. * xp以下的電腦適用
  35. * */
  36. [DllImport("winmm.dll")]
  37. public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
  38.  
  39. [DllImport("winmm.dll")]
  40. public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
  41.  
  42. public static void vol_up()
  43. {
  44. // 設定變數CurrVol用以取得目前音量
  45. uint CurrVol = 0;
  46. // 透過waveOutGetVolume取得目前音量給變數CurrVol
  47. waveOutGetVolume(IntPtr.Zero, out CurrVol);
  48. // 計算音量大小
  49. ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
  50. // 將音量大小分為10階
  51. int vol_value = CalcVol / (ushort.MaxValue / 10);
  52. Console.WriteLine(CalcVol / (ushort.MaxValue / 10));
  53. // 音量值加 1
  54. vol_value = vol_value + 1;
  55. ValueChanged(vol_value);
  56. }
  57.  
  58. public static void vol_down()
  59. {
  60. // 設定變數CurrVol用以取得目前音量
  61. uint CurrVol = 0;
  62. // 透過waveOutGetVolume取得目前音量給變數CurrVol
  63. waveOutGetVolume(IntPtr.Zero, out CurrVol);
  64. // 計算音量大小
  65. ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
  66. // 將音量大小分為10階
  67. int vol_value = CalcVol / (ushort.MaxValue / 10);
  68. Console.WriteLine(CalcVol / (ushort.MaxValue / 10));
  69. // 音量值減 1
  70. vol_value = vol_value - 1;
  71. ValueChanged(vol_value);
  72. }
  73.  
  74. // 值改變時,設定音量
  75. private static void ValueChanged(int value)
  76. {
  77. // 計算要設定的音量大小
  78. int NewVolume = ((ushort.MaxValue / 10) * value);
  79. // 設定相同的數值於左聲道與右聲道
  80. uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
  81. // 設定音量
  82. waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
  83. }
  84. }

留言

這個網誌中的熱門文章

python nn 聲音辨識 -1 傅立葉轉換

android 定時通知(永久長期的) 本篇只講AlarmManager使用

C# 模擬鍵盤滑鼠控制電腦

raspberrypi 開機自動執行程式 與 在terminal開啟第二個terminal執行python

python pyautogui 簡介