1 using System;
2 using System.Runtime.InteropServices;
3 using System.Diagnostics;
4
5 namespace GavinTung
6 {
7 class SystemMultimediaController
8 {
9 /*
10 * 弹出系统音量控制器
11 * */
12 public static void PopupController()
13 {
14 ProcessStartInfo Info = new ProcessStartInfo();
15 Info.FileName = "Sndvol32";
16 Process.Start(Info);
17 }
18
19 /*
20 * 获得音量范围和获取/设置当前音量
21 * */
22 public static int MaxValue
23 {
24 get { return int.Parse(iMaxValue.ToString()); }
25 }
26 public static int MinValue
27 {
28 get { return int.Parse(iMinValue.ToString()); }
29 }
30 public static int CurrentValue
31 {
32 get {
33 GetVolume();
34 return iCurrentValue;
35 }
36 set {
37 SetValue(MaxValue, MinValue, value);
38 }
39 }
40
41
42 #region Private Static Data Members
43 private const UInt32 iMaxValue = 0xFFFF;
44 private const UInt32 iMinValue = 0x0000;
45 private static int iCurrentValue = 0;
46 #endregion
47 #region Private Static Method
48 /*
49 * 得到当前音量
50 **/
51 private static void GetVolume()
52 {
53 UInt32 d, v;
54 d = 0;
55 long i = waveOutGetVolume(d, out v);
56 UInt32 vleft = v & 0xFFFF;
57 UInt32 vright = (v & 0xFFFF0000) >> 16;
58 UInt32 all = vleft | vright;
59 UInt32 value = (all * UInt32.Parse((MaxValue - MinValue).ToString())/((UInt32)iMaxValue));
60 iCurrentValue = int.Parse(value.ToString());
61 }
62
63 /*
64 * 修改音量值
65 * */
66 private static void SetValue(int aMaxValue , int aMinValue, int aValue)
67 {
68 //先把trackbar的value值映射到0x0000~0xFFFF范围
69 UInt32 Value = (UInt32)((double)0xffff * (double)aValue / (double)(aMaxValue - aMinValue));
70 //限制value的取值范围
71 if (Value < 0) Value = 0;
72 if (Value > 0xffff) Value = 0xffff;
73 UInt32 left = (UInt32)Value;//左声道音量
74 UInt32 right = (UInt32)Value;//右
75 waveOutSetVolume(0, left << 16 | right); //"<<"左移,“|”逻辑或运算
76 }
77 #endregion
78 /*
79 * 在winmm.dll中
80 *第一个参数可以为0,表示首选设备
81 *第二个参数为音量:0xFFFF为最大,0x0000为最小,
82 *其中高位(前两位)表示右声道音量,低位(后两位)表示左 声道音量 。
83 */
84 #region Windows Media API
85 [DllImport("winmm.dll")]
86 private static extern long waveOutSetVolume(UInt32 deviceID, UInt32 Volume);
87 [DllImport("winmm.dll")]
88 private static extern long waveOutGetVolume(UInt32 deviceID, out UInt32 Volume);
89 #endregion
90 }
91 }