要設置快捷鍵必須使用user32.dll下面的兩個方法。
bool registerhotkey( //注冊系統熱鍵的api函數
hwnd hwnd,
int id,
uint fsmodifiers,
uint vk
);
bool unregisterhotkey( //刪除系統熱鍵的api函數
hwnd hwnd,
int id
);
在c#中引用命名空間system.runtime.interopservices;來加載非托管類user32.dll
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
namespace hotkey
{
public enum keymodifiers //組合鍵枚舉
{
none = 0,
alt = 1,
control = 2,
shift = 4,
windows = 8
}
public partial class form1 : form
{
/*
* registerhotkey函數原型及說明:
* bool registerhotkey(
* hwnd hwnd, // window to receive hot-key notification
* int id, // identifier of hot key
* uint fsmodifiers, // key-modifier flags
* uint vk // virtual-key code);
* 參數 id為你自己定義的一個id值
* 對一個線程來講其值必需在0x0000 - 0xbfff范圍之內,十進制為0~49151
* 對dll來講其值必需在0xc000 - 0xffff 范圍之內,十進制為49152~65535
* 在同一進程內該值必須唯一參數 fsmodifiers指明與熱鍵聯合使用按鍵
* 可取值為:mod_alt mod_control mod_win mod_shift參數,或數字0為無,1為alt,2為control,4為shift,8為windows
* vk指明熱鍵的虛擬鍵碼
*/
[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
);
public form1()
{
initializecomponent();
}
private void processhotkey(message m) //按下設定的鍵時調用該函數
{
intptr id = m.wparam; //intptr用于表示指針或句柄的平臺特定類型
//messagebox.show(id.tostring());
string sid = id.tostring();
switch (sid)
{
case "100":
messagebox.show("調用a函數");
break;
case "200":
messagebox.show("調用b函數");
break;
}
}
private void form1_load(object sender, eventargs e)
{
//handle為當前窗口的句柄,繼續自control.handle,control為定義控件的基類
//registerhotkey(handle, 100, 0, keys.a); //注冊快捷鍵,熱鍵為a
//registerhotkey(handle, 100, keymodifiers.alt | keymodifiers.control, keys.b);//這時熱鍵為alt+ctrl+b
//registerhotkey(handle, 100, 1, keys.b); //1為alt鍵,熱鍵為alt+b
registerhotkey(handle, 100, 2,keys.a); //定義熱鍵為alt+tab,這里實現了屏幕系統alt+tab鍵
registerhotkey(handle, 200, 2, keys.b); //注冊2個熱鍵,根據id值100,200來判斷需要執行哪個函數
}
private void button1_click(object sender, eventargs e) //重新設置熱鍵
{
unregisterhotkey(handle, 100);//卸載快捷鍵
registerhotkey(handle, 100, 2, keys.c); //注冊新的快捷鍵,參數0表示無組合鍵
}
private void form1_formclosing(object sender, formclosingeventargs e) //退出程序時缷載熱鍵
{
unregisterhotkey(handle, 100);//卸載第1個快捷鍵
unregisterhotkey(handle, 200); //缷載第2個快捷鍵
}
//重寫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
}
}
}
新聞熱點
疑難解答