1.首先引入System.Runtime.InteropServices
using System.Runtime.InteropServices; |
2.在類內部聲明兩個API函數,它們的位置和類的成員變數等同.
[System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函數 public static extern bool ReGISterHotKey( IntPtr hWnd, // handle to window int id, // hot key identifier uint fsModifiers, // key-modifier options Keys vk // virtual-key code ); [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函數 public static extern bool UnregisterHotKey( IntPtr hWnd, // handle to window int id // hot key identifier ); |
3.定義一個KeyModifiers的枚舉,以便出現按鍵組合
public enum KeyModifiers { None = 0, Alt = 1, Control = 2, Shift = 4, Windows = 8 } |
4.在類的建構函式出註冊系統熱鍵
樣本,下例註冊了四個熱鍵:
public MainForm() { InitializeComponent(); RegisterHotKey(Handle, 100, 2, Keys.Left); // 熱鍵一:Control +游標左箭頭 RegisterHotKey(Handle, 200, 2, Keys.Right); / /熱鍵一:Control +游標右箭頭 RegisterHotKey(Handle, 300, 2, Keys.Up); // 熱鍵一:Control +游標上箭頭 RegisterHotKey(Handle, 400, 2, Keys.Down); // 熱鍵一:Control +游標下箭頭 ....; } |
5.重寫WndProc()方法,通過監視系統訊息,來調用過程
樣本:
protected override void WndProc(ref Message m)//監視Windows訊息 { const int WM_HOTKEY = 0x0312; //如果m.Msg的值為0x0312那麼表示使用者按下了熱鍵 switch (m.Msg) { case WM_HOTKEY: ProcessHotkey(m); //按下熱鍵時調用ProcessHotkey()函數 break; } base.WndProc(ref m); //將系統訊息傳遞自父類的WndProc } |
5.不用說,我們接下來需要實現ProcessHotkey函數:
//按下設定的鍵時調用該函數 private void ProcessHotkey(Message m) { IntPtr id = m.WParam; //IntPtr用於表示指標或控制代碼的平台特定類型 //MessageBox.Show(id.ToString()); string sid = id.ToString(); switch (sid) { case "100": DecreseVolumnb(); break; // 按下Control +游標左箭頭,調用函數DecreseVolumnb(); case "200": AddVolumnb(); break; // 按下Control +游標右箭頭,調用函數AddVolumnb() case "300":// 按下Control +游標上箭頭,顯示表單 this.Visible = true; break; case "400":// 按下Control +游標下箭頭,隱藏表單 this.Visible = false; break; } } |
很明顯接下來分別實現函數DecreseVolumnb(); 和AddVolumnb(); 即可.
6.最後別忘了在程式退出時取消熱鍵的註冊
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { UnregisterHotKey(Handle, 100); //卸載第1個快速鍵 UnregisterHotKey(Handle, 200); //缷載第2個快速鍵 UnregisterHotKey(Handle, 300); //卸載第3個快速鍵 UnregisterHotKey(Handle, 400); //缷載第4個快速鍵 } |
以上就是在C#程式中使用系統熱鍵的整個過程。