Winform为窗体增加快捷键

1. 定义窗体的 xxx_KeyDown(object sender, EventArgs e)

   

2. 书写快捷键的代码:

   

//这里的xxx代表你的窗体名
private void xxxx_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.D1:
                    chk32bit.Checked = !chk32bit.Checked;
                    break;
                case Keys.D2:
                    chk64bit.Checked = !chk64bit.Checked;
                    break;
                case Keys.D3:
                    chkXP.Checked = !chkXP.Checked;
                    break;
                case Keys.D4:
                    chkVista.Checked = !chkVista.Checked;
                    break;
                case Keys.D5:
                    chkWin7.Checked = !chkWin7.Checked;
                    break;
                case Keys.D6:
                    chkWin8.Checked = !chkWin8.Checked;
                    break;
                case Keys.D7:
                    chkWin81.Checked = !chkWin81.Checked;
                    break;
                case Keys.D8:
                    chkWin10.Checked = !chkWin10.Checked;
                    break;

            }

            e.Handled = false;
        
        }

  3. 最关键的,设置窗体的 KeyPreview=true (一句话,不设置就不行)

         Form.KeyPreview 属性 :获取或设置一个值,该值指示在将键事件传递到具有焦点的控件前,窗体是否将接收此键事件。

     4.  设置完的代码片段如下:

// 
// Form1
// 
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.KeyPreview = true;
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
this.ResumeLayout(false);

  

         

 

posted @ 2015-09-22 18:03  一菲聪天  阅读(685)  评论(0编辑  收藏  举报