注册快捷键,简言之,就是为程序制作快捷键,可以起到监控键盘事件的作用。很多软件都带热键功能的,通过以下代码可以实现2个键或3个键的快捷键。

    这是昨天用C#写机顶盒控制系统音量时,写的代码。附上共享。

 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 VolumnModify
{
    public partial class Form1 : Form
    {
        //注册热键的api
        [DllImport("user32.dll")]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk);
        [DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        //系统音量API
        [DllImport("winmm.dll")]
        public static extern UInt32 waveOutSetVolume(UInt32 deviceID, UInt32 Volume); //设置音量
        [DllImport("winmm.dll")]
        public static extern UInt32 waveOutGetVolume(UInt32 deviceID, ref UInt32 Volume); //获取音量

         public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //窗体锚定在0,0
            this.Location = new Point(-100, -100);

            this.Height = 20;
            this.Width = 20;
            this.Activate();

            //注册热键(窗体句柄,热键ID,辅助键,实键)
            RegisterHotKey(this.Handle, 225, 0, Keys.VolumeUp);
            RegisterHotKey(this.Handle, 226, 0, Keys.VolumeDown);
            RegisterHotKey(this.Handle, 227, 0, Keys.VolumeMute);

          }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x0312:    //这个是window消息定义的注册的热键消息
                    if (m.WParam.ToString().Equals("225"))  //提高音量热键
                    {
                         MessageBox.Show("你按了VolumeUp ");
                    }
                    else if (m.WParam.ToString().Equals("226"))  //降低音量热键
                    {

                         MessageBox.Show("你按了VolumeDown ");
                    }
                    else if (m.WParam.ToString().Equals("227"))  //静音热键
                    {
                         MessageBox.Show("你按了VolumeMute");
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //注消热键(句柄,热键ID)
            UnregisterHotKey(this.Handle, 225);
            UnregisterHotKey(this.Handle, 226);
            UnregisterHotKey(this.Handle, 227);
        }
    }
}

posted on 2009-06-16 11:13  GT_Andy  阅读(4779)  评论(0编辑  收藏  举报