首页 > 技术文章 > 设置快捷键(3种方式)

wwz-wwz 2017-10-09 16:02 原文

(1)设置快捷键并显示出来

 MenuStrip ms = new MenuStrip();
            ToolStripMenuItem tm1 = new ToolStripMenuItem("你好");

            ToolStripMenuItem tl1 = new ToolStripMenuItem("你好1");
            tl1.Click += Tl1_Click;
            tl1.ShowShortcutKeys = true;
            //tl1.ShortcutKeyDisplayString = "你好1的ShortcutKeyDisplayString"; 如果ShortcutKeyDisplayString为空,就显示快捷键;反之显示为ShortcutKeyDisplayString的值
            tl1.ShortcutKeyDisplayString = null;
            tl1.ShortcutKeys = Keys.Control | Keys.A;

            tm1.DropDownItems.Add(tl1);
            ms.Items.Add(tm1);
            this.Controls.Add(ms);
        }

        private void Tl1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("你好1的单击事件");
        }
View Code

(2)KeyDown事件

    缺点:当程序失去焦点的时候这个热键(快捷键)就不管用了!

private void TextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                //操作
            }
        }
View Code

(3)注册和注销系统热键

①添加HotKey类

 class HotKey
    {
        //如果函数执行成功,返回值不为0。  
        //如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。  
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(
            IntPtr hWnd,                 //要定义热键的窗口的句柄  
            int id,                      //定义热键ID(不能与其它ID重复)            
            KeyModifiers fsModifiers,    //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效  
            Keys vk                      //定义热键的内容  
            );

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd,                 //要取消热键的窗口的句柄  
            int id                       //要取消热键的ID  
            );

        //定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)  
        [Flags()]
        public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            WindowsKey = 8
        }
    }
View Code

②设置快捷键和事件

 private void Form1_Activated(object sender, EventArgs e)
        {
            HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Ctrl, Keys.A);//注册事件 100随意写,保证不重复。
        }

        private void Form1_Leave(object sender, EventArgs e)
        {
            HotKey.UnregisterHotKey(Handle, 100);//注销事件
        }
        protected override void WndProc(ref Message m)
        {
            switch (m.WParam.ToInt32())
            {
                case 100:
                    MessageBox.Show("???");//执行事件
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
View Code

完!

 

推荐阅读