1.首先引入System.Runtime.InteropServices
using System.Runtime.InteropServices;
2.在類內(nèi)部聲明兩個(gè)API函數(shù),它們的位置和類的成員變量等同.
[System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函數(shù)
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函數(shù)
public static extern bool UnregisterHotKey(
IntPtr hWnd, // handle to window
int id // hot key identifier
);
3.定義一個(gè)KeyModifiers的枚舉,以便出現(xiàn)組合鍵
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
4.在類的構(gòu)造函數(shù)出注冊(cè)系統(tǒng)熱鍵
示例,下例注冊(cè)了四個(gè)熱鍵:
public MainForm()
{
InitializeComponent();
RegisterHotKey(Handle, 100, 2, Keys.Left); // 熱鍵一:Control +光標(biāo)左箭頭
RegisterHotKey(Handle, 200, 2, Keys.Right); / /熱鍵一:Control +光標(biāo)右箭頭
RegisterHotKey(Handle, 300, 2, Keys.Up); // 熱鍵一:Control +光標(biāo)上箭頭
RegisterHotKey(Handle, 400, 2, Keys.Down); // 熱鍵一:Control +光標(biāo)下箭頭
....;
}
5.重寫WndProc()方法,通過監(jiān)視系統(tǒng)消息,來(lái)調(diào)用過程
示例:
protected override void WndProc(ref Message m)//監(jiān)視Windows消息
{
const int WM_HOTKEY = 0x0312; //如果m.Msg的值為0x0312那么表示用戶按下了熱鍵
switch (m.Msg)
{
case WM_HOTKEY:
ProcessHotkey(m); //按下熱鍵時(shí)調(diào)用ProcessHotkey()函數(shù)
break;
}
base.WndProc(ref m); //將系統(tǒng)消息傳遞自父類的WndProc
}
5.不用說(shuō),我們接下來(lái)需要實(shí)現(xiàn)ProcessHotkey函數(shù):
//按下設(shè)定的鍵時(shí)調(diào)用該函數(shù)
private void ProcessHotkey(Message m)
{
IntPtr id = m.WParam; //IntPtr用于表示指針或句柄的平臺(tái)特定類型
//MessageBox.Show(id.ToString());
string sid = id.ToString();
switch (sid)
{
case "100": DecreseVolumnb(); break; // 按下Control +光標(biāo)左箭頭,調(diào)用函數(shù)DecreseVolumnb();
case "200": AddVolumnb(); break; // 按下Control +光標(biāo)右箭頭,調(diào)用函數(shù)AddVolumnb()
case "300":// 按下Control +光標(biāo)上箭頭,顯示窗體
this.Visible = true;
break;
case "400":// 按下Control +光標(biāo)下箭頭,隱藏窗體
this.Visible = false;
break;
}
}
很明顯接下來(lái)分別實(shí)現(xiàn)函數(shù)DecreseVolumnb(); 和AddVolumnb(); 即可.
6.最后別忘了在程序退出時(shí)取消熱鍵的注冊(cè)
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(Handle, 100); //卸載第1個(gè)快捷鍵
UnregisterHotKey(Handle, 200); //缷載第2個(gè)快捷鍵
UnregisterHotKey(Handle, 300); //卸載第3個(gè)快捷鍵
UnregisterHotKey(Handle, 400); //缷載第4個(gè)快捷鍵
}
以上就是在C#程序中使用系統(tǒng)熱鍵的整個(gè)過程。