C#编程实现自定义热键的方法
程序员文章站
2023-11-25 15:29:46
本文实例讲述了c#编程实现自定义热键的方法。分享给大家供大家参考。具体实现方法如下:
using system;
using system.collection...
本文实例讲述了c#编程实现自定义热键的方法。分享给大家供大家参考。具体实现方法如下:
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; using system.drawing.imaging; using system.io; using system.runtime.interopservices; using system.net; using system.drawing.drawing2d; namespace app { public partial class form2 : form { public form2() { initializecomponent(); //程序加载加载热键 this.load += delegate { // 热键一:control +光标左箭头 customsystemkeyboard.registerhotkey(handle, 100, 8, keys.left); // 热键一:control +光标右箭头 customsystemkeyboard.registerhotkey(handle, 200, 2, keys.right); // 热键一:control +光标上箭头 customsystemkeyboard.registerhotkey(handle, 300, 2, keys.up); // 热键一:control +光标下箭头 customsystemkeyboard.registerhotkey(handle, 400, 2, keys.down); }; //在程序退出时取消热键的注册 this.formclosing += delegate { customsystemkeyboard.unregisterhotkey(handle, 100); customsystemkeyboard.unregisterhotkey(handle, 200); customsystemkeyboard.unregisterhotkey(handle, 300); customsystemkeyboard.unregisterhotkey(handle, 400); }; } protected override void wndproc(ref message m) { //如果m.msg的值为0x0312那么表示用户按下了热键 const int wm_hotkey = 0x0312; switch (m.msg) { case wm_hotkey: processkey(m); break; } base.wndproc(ref m); } /// <summary> /// 按下热键的操作 /// </summary> /// <param name="m"></param> protected void processkey(message m) { //intptr用于表示指针或句柄的平台特定类型 string id = m.wparam.tostring(); messagebox.show(id); switch (id) { case "100": // break; case "200": break; case "300": break; case "400": break; } } } public class customsystemkeyboard { /// <summary> /// 声明api函数 /// </summary> /// <param name="hwnd">handle</param> /// <param name="id">热键id</param> /// <param name="fsmodifiers">热键类型(keymodifiers)</param> /// <param name="vk">键盘按键</param> /// <returns></returns> [system.runtime.interopservices.dllimport("user32.dll")] public static extern bool registerhotkey( intptr hwnd, int id, uint fsmodifiers, keys vk ); /// <summary> /// 声明api函数 /// </summary> /// <param name="hwnd"></param> /// <param name="id"></param> /// <returns></returns> [system.runtime.interopservices.dllimport("user32.dll")] public static extern bool unregisterhotkey(intptr hwnd, int id); /// <summary> /// 定义一个keymodifiers的枚举,以便出现组合键 /// </summary> public enum keymodifiers { none = 0, alt = 1, control = 2, shift = 3, windows = 8 } } }
希望本文所述对大家的c#程序设计有所帮助。