当前位置: 代码迷 >> C# >> 替个按钮定义快捷键F1-9
  详细解决方案

替个按钮定义快捷键F1-9

热度:431   发布时间:2016-05-05 05:31:04.0
为个按钮定义快捷键F1-9
可以用(&A)
 如果,想为这个按钮设置快捷键为"F9"呢,应该怎样搞?
------解决思路----------------------
第一 ,用api函数RegisterHotKey
http://blog.sina.com.cn/s/blog_674a665801013hit.html
第二,自己拦截按键消息,判断是哪个键,然后执行不同的代码
------解决思路----------------------
KeyDown事件里判断按键,或者截获消息里做判断
------解决思路----------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("F9被按下~~~");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.KeyPreview = true;
            this.KeyDown += new KeyEventHandler(Form1_KeyDown);
        }

        void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if( e.KeyCode== Keys.F9)
            {                
                button1.PerformClick();
            }
        }
    }
}

------解决思路----------------------
直接处理KeyPress就可以了

Alt+键 那个不叫快捷键,叫加速键。
------解决思路----------------------
这种快捷键最好是override  ProcessCmdKey  方法,这是winform设计上用来处理快捷键的地方,可以最早截获消息。

还有个另类方法,只需要在设计器里面操作。拖一个MenuStrip,Visible设置成false,添加菜单项,把ShortcutKeys属性设置成需要的快捷键,然后在Click事件那里选择对应button的Click事件处理方法。
------解决思路----------------------
1.ProcessCmdKey,ProcessDialogKey;
2.有些第三方控件提供的组件有快捷键功能,如DevExpress的BarManager可以为上面的按钮提供Shortcut
  相关解决方案