C# Winform 开发框架集成快捷键功能 (Hotkey)
作者:C/S框架网  发布日期:2011/06/16 15:59:52
  C# Winform 开发框架集成快捷键功能 (Hotkey)

C# Winform 开发框架集成快捷键功能 (Hotkey)


有两种做法:


1. Windows 勾子,参考:C# 注册系统热键/快捷键(MainForm HotKey) 
   此方案有个缺点,会强制占用其它软件的热键,比如:Ctrl+C。


2. Form.KeyDown事件,需要设置Form.KeyPreview为True。


注意:Ctrl键容易与OS系统的热键冲突,建议改为Alt键。



贴图图片




开发框架内是使用KeyDown事件集成快捷键功能的,代码如下:

frmBase:

C# Code:

//处理用户按键事件

private void frmBase_KeyDown(object sender, KeyEventArgs e)

{

  if (e.Alt && (e.KeyCode >= Keys.A) && (e.KeyCode < Keys.Z))

  {

    this.DoExecuteHotKey(e);

    return;

  }

}


protected virtual void DoExecuteHotKey(KeyEventArgs e)

{

  //虚拟方法,由派生窗体处理自己的热键。

}



frmBaseChild:

C# Code:

        protected override void DoExecuteHotKey(KeyEventArgs e)

        {

            if (e.Alt)

            {

                if (e.KeyCode == Keys.H) this.DoHelp(null); //Ctrl+H:帮助

                else if (e.KeyCode == Keys.X) this.DoClose(null);//Ctrl+X:关闭

                else base.DoExecuteHotKey(e);

            }

        }



frmBaseDataForm:
 

C# Code:

protected override void DoExecuteHotKey(KeyEventArgs e)

        {

            if (e.Alt)

            {

                if (e.KeyCode == Keys.V) this.DoViewContent(_buttons.GetButtonByName("btnView"));//查看

                else if (e.KeyCode == Keys.N) this.DoAdd(_buttons.GetButtonByName("btnAdd"));//新增

                else if (e.KeyCode == Keys.D) this.DoDelete(_buttons.GetButtonByName("btnDelete"));//删除

                else if (e.KeyCode == Keys.E) this.DoEdit(_buttons.GetButtonByName("btnEdit"));//修改

                else if (e.KeyCode == Keys.P) this.DoPrint(_buttons.GetButtonByName("btnPrint"));//打印

                else if (e.KeyCode == Keys.S) this.DoSave(_buttons.GetButtonByName("btnSave"));//保存

                else if (e.KeyCode == Keys.C) this.DoCancel(_buttons.GetButtonByName("btnCancel"));//取消

                else base.DoExecuteHotKey(e);//由基类处理

            }

        }



//来源:C/S框架网(www.csframework.com) QQ:1980854898




C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务

上一篇 下一篇