[C#]運用WinAPI控制電腦靜音與音量

  • 13356
  • 0
  • 2012-01-28

運用WinAPI控制電腦靜音與音量

在小舖中看到關於靜音的問題,所以想要寫個小程式做音量控制與靜音,此功能可以透過 WinAPI 來達成,以下為程式碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace WindowsApplication7
{

    public partial class Form1 : Form
    {
      
        public Form1()
        {
            InitializeComponent();
        }


        // 宣告常式
        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);
        
        private void btnVup_Click(object sender, EventArgs e)
        {
            // 聲音變大
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_UP);
        }


        private void btnVdown_Click(object sender, EventArgs e)
        {
            // 聲音變小
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_DOWN);
        }


        private void btnMute_Click(object sender, EventArgs e)
        {
            // 靜音
            SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
        }

    }

}

參考

http://blog.csdn.net/alexzhang00/archive/2009/02/25/3937098.aspx