InPowerS.Net

 找回密碼
 註冊
搜索
查看: 1990|回復: 0

在Visual C#程序中使用系统热键

[複製鏈接]
發表於 2009-6-23 11:40:36 | 顯示全部樓層 |閱讀模式
本帖最後由 肥龍 於 2009-6-23 11:42 編輯

在Visual C#程序中使用系统热键
1.首先引入System.Runtime.InteropServices
  1. using System.Runtime.InteropServices;
複製代碼

2.在类内部声明两个API函数,它们的位置和类的成员变量等同.
  1. [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数  
  2. public static extern bool RegisterHotKey(
  3. IntPtr hWnd, // handle to window  
  4. int id, // hot key identifier  
  5. uint fsModifiers, // key-modifier options  
  6. Keys vk // virtual-key code  
  7. );
  8. [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数  
  9. public static extern bool UnregisterHotKey(
  10. IntPtr hWnd, // handle to window  
  11. int id // hot key identifier  
  12. );  
複製代碼


3.定义一个KeyModifiers的枚举,以便出现组合键
  1. public enum KeyModifiers
  2. {
  3.  None = 0,
  4.  Alt = 1,
  5.  Control = 2,
  6.  Shift = 4,
  7.  Windows = 8
  8. }  
複製代碼
4.在类的构造函数出注册系统热键,下例注册了四个热键:
  1. public MainForm()
  2. {
  3.  InitializeComponent();  
  4.  RegisterHotKey(Handle, 100, 2, Keys.Left); // 热键一:Control +光标左箭头
  5.  RegisterHotKey(Handle, 200, 2, Keys.Right); / /热键一:Control +光标右箭头
  6.  RegisterHotKey(Handle, 300, 2, Keys.Up); // 热键一:Control +光标上箭头
  7.  RegisterHotKey(Handle, 400, 2, Keys.Down); // 热键一:Control +光标下箭头
  8.  ....;  
  9. }  
複製代碼
5.重写WndProc()方法,通过监视系统消息,来调用过程,示例:
  1. protected override void WndProc(ref Message m)//监视Windows消息  
  2. {  
  3.  const int WM_HOTKEY = 0x0312; //如果m.Msg的值为0x0312那么表示用户按下了热键  
  4.  switch (m.Msg)  
  5.  {  
  6.   case WM_HOTKEY:  
  7.   ProcessHotkey(m); //按下热键时调用ProcessHotkey()函数
  8.   break;  
  9.  }  
  10.  base.WndProc(ref m); //将系统消息传递自父类的WndProc  
  11. }   
複製代碼
5.不用说,我们接下来需要实现ProcessHotkey函数:
  1. //按下设定的键时调用该函数  
  2. private void ProcessHotkey(Message m)  
  3. {
  4.  IntPtr id = m.WParam; //IntPtr用于表示指针或句柄的平台特定类型  
  5.  //MessageBox.Show(id.ToString());  
  6.  string sid = id.ToString();  
  7.  switch (sid)
  8.  {
  9.   case "100": DecreseVolumnb(); break; // 按下Control +光标左箭头,调用函数DecreseVolumnb();  
  10.   case "200": AddVolumnb(); break; // 按下Control +光标右箭头,调用函数AddVolumnb()
  11.   case "300":// 按下Control +光标上箭头,显示窗体
  12.    this.Visible = true;  
  13.    break;  
  14.   case "400":// 按下Control +光标下箭头,隐藏窗体
  15.    this.Visible = false;  
  16.    break;  
  17.  }  
  18. }  
複製代碼
  很明显接下来分别实现函数DecreseVolumnb(); 和AddVolumnb(); 即可.
  6.最后别忘了在程序退出时取消热键的注册
  1. private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
  2. {
  3.  UnregisterHotKey(Handle, 100); //卸载第1个快捷键  
  4.  UnregisterHotKey(Handle, 200); //缷载第2个快捷键
  5.  UnregisterHotKey(Handle, 300); //卸载第3个快捷键  
  6.  UnregisterHotKey(Handle, 400); //缷载第4个快捷键
  7. }  
複製代碼
  以上就是在C#程序中使用系统热键的整个过程
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

小黑屋|Archiver|手機版|InPowerS.Net

GMT+8, 2025-4-11 20:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回復 返回頂部 返回列表