最近找了一些資料,是講在C#中設定快速鍵運行方法或程式的
要設定快速鍵必須使用user32.dll下面的兩個方法。
BOOL RegisterHotKey(
HWND hWnd,
int id,
UINT fsModifiers,
UINT vk
);
和
BOOL UnregisterHotKey(
HWND hWnd,
int id
);
轉換成C#代碼,那麼首先就要引用命名空間System.Runtime.InteropServices;來載入非託管類user32.dll。於是有了:
[DllImport("user32.dll", SetLastError=true)]
public static extern bool RegisterHotKey(
IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers fsModifiers, // key-modifier options
Keys vk // virtual-key code
);
[DllImport("user32.dll", SetLastError=true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd, // handle to window
int id // hot key identifier
);
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
這是註冊和卸載全域快速鍵的方法,那麼我們只需要在Form_Load的時候加上註冊快速鍵的語句,在FormClosing的時候卸載全域快速鍵。同時,為了保證剪貼簿的內容不受到其他程式調用剪貼簿的幹擾,在Form_Load的時候,我先將剪貼簿裡面的內容清空。
於是有了:
private void Form1_Load(object sender, System.EventArgs e)
{
label2.AutoSize = true;
Clipboard.Clear();//先清空剪貼簿防止剪貼簿裡面先複製了其他內容
RegisterHotKey(Handle, 100, 0, Keys.F10);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(Handle, 100);//卸載快速鍵
}
那麼我們在別的視窗,怎麼讓按了快速鍵以後調用我的主過程ProcessHotkey()呢?
那麼我們就必須重寫WndProc()方法,通過監視系統訊息,來調用過程:
protected override void WndProc(ref Message m)//監視Windows訊息
{
const int WM_HOTKEY = 0x0312;//按快速鍵
switch (m.Msg)
{
case WM_HOTKEY:
ProcessHotkey();//調用主處理常式
break;
}
base.WndProc(ref m);
}