设置C#快捷键的两种方法

设置C#快捷键的两种方法是:

 
 
 
  1. BOOL RegisterHotKey(  
  2.   HWND hWnd,  
  3.   int id,  
  4.   UINT fsModifiers,  
  5.   UINT vk  
  6.   );   
  7.   和  
  8.   BOOL UnregisterHotKey(  
  9.   HWND hWnd,  
  10.   int id  
  11.   );  

转换成C#代码,那么首先就要引用 命名空间 System.Runtime.InteropServices;来 加载 非托管类user32.dll。于是有了:

 
 
 
  1.   [DllImport("user32.dll", SetLastError=true)]   
  2.   public static extern bool RegisterHotKey(  
  3.   IntPtr hWnd, // handle to window   
  4.   int id, // hot key identifier   
  5.   KeyModifiers fsModifiers, // key-modifier options   
  6.   Keys vk // virtual-key code   
  7.   );   
  8.   [DllImport("user32.dll", SetLastError=true)]   
  9.   public static extern bool UnregisterHotKey(  
  10.   IntPtr hWnd, // handle to window   
  11.   int id // hot key identifier   
  12.   );  
  13.   [Flags()]   
  14.   public enum KeyModifiers   
  15.   {   
  16.   None = 0,   
  17.   Alt = 1,   
  18.   Control = 2,   
  19.   Shift = 4,   
  20.   Windows = 8   
  21.   }  

这是注册和卸载全局C#快捷键的方法,那么我们只需要在Form_Load的时候加上注册快捷键的语句,在FormClosing的时候卸载全局快捷键。同时,为了保证剪贴板的内容不受到其他程序调用剪贴板的干扰,在Form_Load的时候,我先将剪贴板里面的内容清空。

于是有了:

 
 
 
  1.   private void Form1_Load(object sender, System.EventArgs e)  
  2.   {  
  3.   label2.AutoSize = true;  
  4.   Clipboard.Clear();//先清空剪贴板防止剪贴板里面先复制了其他内容  
  5.   RegisterHotKey(Handle, 100, 0, Keys.F10);  
  6.   }  
  7.   private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
  8.   {  
  9.   UnregisterHotKey(Handle, 100);//卸载快捷键  
  10.   }  

那么我们在别的窗口,怎么让按了快捷键以后调用 我的 主过程ProcessHotkey()呢?

那么我们就必须重写WndProc()方法,通过监视系统消息,来调用过程:

 
 
 
  1.   protected override void WndProc(ref Message m)//监视Windows消息  
  2.   {  
  3.   const int WM_HOTKEY = 0x0312;//按快捷键  
  4.   switch (m.Msg)  
  5.   {  
  6.   case WM_HOTKEY:  
  7.   ProcessHotkey();//调用主处理程序  
  8.   break;  
  9.   }  
  10.   base.WndProc(ref m);  
  11.   }  

这样我的C#快捷键程序就完成了。

【编辑推荐】

  1. 如何用C#和ADO.NET访问
  2. 浅析C# Switch语句
  3. C#验证输入方法详解
  4. 简单介绍C# 匿名方法
  5. C# FileSystemWatcher对象
THE END