簡單說明一下:
“public static extern bool RegisterHotKey()”這個函數用於註冊熱鍵。由於這個函數需要引用user32.dll動態鏈接庫後才能使用,並且
user32.dll是非託管代碼,不能用命名空間的方式直接引用,所以需要用“DllImport”進行引入後才能使用。於是在函數前面需要加上
“[DllImport("user32.dll", SetLastError = true)]”這行語句。
“public static extern bool UnregisterHotKey()”這個函數用於註銷熱鍵,同理也需要用DllImport引用user32.dll後才能使用。
“public enum KeyModifiers{}”定義了一組枚舉,將輔助鍵的數字代碼直接表示爲文字,以方便使用。這樣在調用時我們不必記住每一個輔
助鍵的代碼而只需直接選擇其名稱即可。
(1)建立一個類文件,命名爲HotKey.cs,代碼如下:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace KoalaStudio.BookshopManager
{
class HotKey
{
//如果函數執行成功,返回值不爲0。
//如果函數執行失敗,返回值爲0。要得到擴展錯誤信息,調用GetLastError。
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd, //要定義熱鍵的窗口的句柄
int id, //定義熱鍵ID(不能與其它ID重複)
KeyModifiers fsModifiers, //標識熱鍵是否在按Alt、Ctrl、Shift、Windows等鍵時纔會生效
Keys vk //定義熱鍵的內容
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd, //要取消熱鍵的窗口的句柄
int id //要取消熱鍵的ID
);
//定義了輔助鍵的名稱(將數字轉變爲字符以便於記憶,也可去除此枚舉而直接使用數值)
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Ctrl = 2,
Shift = 4,
WindowsKey = 8
}
}
}
(2)以窗體FormA爲例,介紹HotKey類的使用
在FormA的Activate事件中註冊熱鍵,本例中註冊Shift+S,Ctrl+Z,Alt+D這三個熱鍵。這裏的Id號可任意設置,但要保證不被重複。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace KoalaStudio.BookshopManager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form_Activated(object sender, EventArgs e)
{
//註冊熱鍵Shift+S,Id號爲100。HotKey.KeyModifiers.Shift也可以直接使用數字4來表示。
HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Shift, Keys.S);
//註冊熱鍵Ctrl+B,Id號爲101。HotKey.KeyModifiers.Ctrl也可以直接使用數字2來表示。
HotKey.RegisterHotKey(Handle, 101, HotKey.KeyModifiers.Ctrl, Keys.B);
//註冊熱鍵Alt+D,Id號爲102。HotKey.KeyModifiers.Alt也可以直接使用數字1來表示。
HotKey.RegisterHotKey(Handle, 102, HotKey.KeyModifiers.Alt, Keys.D);
}
private void FrmSale_Leave(object sender, EventArgs e)
{
//註銷Id號爲100的熱鍵設定
HotKey.UnregisterHotKey(Handle, 100);
//註銷Id號爲101的熱鍵設定
HotKey.UnregisterHotKey(Handle, 101);
//註銷Id號爲102的熱鍵設定
HotKey.UnregisterHotKey(Handle, 102);
}
///
/// 監視Windows消息
/// 重載WndProc方法,用於實現熱鍵響應
///
///
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
//按快捷鍵
switch (m.Msg)
{
case WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case 100: //按下的是Shift+S
//此處填寫快捷鍵響應代碼
this.WindowState = FormWindowState.Normal;
this.Show();
break;
case 101: //按下的是Ctrl+B
//此處填寫快捷鍵響應代碼
break;
case 102: //按下的是Alt+D
//此處填寫快捷鍵響應代碼
break;
}
break;
}
base.WndProc(ref m);
}
}
}
完成代碼後,我們在窗體中按下Shift+S、Ctrl+B、Alt+D這三組快捷鍵中的任意一組時,程序都會做出響應的反應。