2013/05/22

C#.Net 用WinAPI控制音量

利用WinAPI去控制音量大小,用SendMessage函式控制系統音量大小
測試環境是W7 32bit企業版本,可以成功使用
如果你要用Unicode編碼就用SendMessageW,用ANSI就用SendMessageA



using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Control_Audio
{
    public partial class Form1 : Form
    {
        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;

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
       
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonVolumeDown_Click(object sender, EventArgs e)
        {
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_DOWN);
        }

        private void buttonVolumeUp_Click(object sender, EventArgs e)
        {
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_UP);
        }

        private void buttonVolumeMute_Click(object sender, EventArgs e)
        {
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
        }
    }
}



參考資料:
http://www.dotblogs.com.tw/chou/archive/2009/03/28/7738.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950(v=vs.85).aspx