本來聽說winapi裡面的RegisterHotKey有時候不好使,於是打算用hook鍵盤消 息來做hook key,結果發現hook那裡處理消息那裡還挺麻煩,也想會不會造成系 統的額外開銷比較大,所以最後用RegisterHotKey來封裝了一下,測試沒有問題 ,還是可以的。(winform)
下面的代碼包括一個Textbox的處理,和一個 封裝了api的類。Textbox那裡就是處理用戶定義的熱鍵的界面表示,比如用戶按 鍵的時候會出現"Ctrl+Alt+A"之類的,Api封裝那裡做了處理,只管 Register好了,不用管UnRegister,當注冊一個一樣的Id的hotkey,會自動先 UnRegister原來的,然後最後關閉窗口的時候,調用一下HotkeyHelper.Dispose ()就可以了。還希望多加建議。here we go..
----------------------- ---------------------------------------------------------
Textbox 部分:(Key hotkeyVk = null; )
private void txbHotKey_KeyDown(object sender, KeyEventArgs e)
{
txbHotKey.Text = string.Empty;
if (e.Control)
{
txbHotKey.Text += "Ctrl+";
}
if (e.Alt)
{
txbHotKey.Text += "Alt+";
}
if (e.Shift)
{
txbHotKey.Text += "Shift+";
}
if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z)
{
if (e.ModifIErs != Keys.None)
{
txbHotKey.Text += e.KeyCode.ToString();
hotkeyVk = e.KeyCode;
}
}
else if (e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9)
{
if (e.ModifIErs != Keys.None)
{
txbHotKey.Text += e.KeyCode.ToString().Remove(0, 1);
hotkeyVk = e.KeyCode;
}
}
else if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
{
if (e.ModifIErs != Keys.None)
{
txbHotKey.Text += e.KeyCode.ToString ().Replace("Pad", "");
hotkeyVk = e.KeyCode;
}
}
else if (e.KeyCode >= Keys.F1 && e.KeyCode <= Keys.F12)
{
txbHotKey.Text += e.KeyCode.ToString();
hotkeyVk = e.KeyCode;
}
e.SuppressKeyPress = false;
e.Handled = true;
}
private void txbHotKey_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void txbHotKey_KeyUp (object sender, KeyEventArgs e)
{
CheckHotkey();
}
void txbHotKey_LostFocus(object sender, EventArgs e)
{
CheckHotkey();
}
private void CheckHotkey()
{
if (txbHotKey.Text.EndsWith("+") || txbHotKey.Text == string.Empty)
{
txbHotKey.Text = "無";
}
}
private void btnHotKey_Click(object sender, EventArgs e)
{
string hotkey = txbHotKey.Text.Replace("+", "");
if (hotkey != "無" && hotkey != string.Empty)
{
uint modifIEs = 0;
if (hotkey.Contains ("Ctrl"))
{
modifIEs |= HotkeyHelper.MOD_CONTROL;
hotkey = hotkey.Replace ("Ctrl", "");
}
if (hotkey.Contains ("Alt"))
{
modifIEs |= HotkeyHelper.MOD_ALT;
hotkey = hotkey.Replace("Alt", "");
}
if (hotkey.Contains("Shift"))
{
modifIEs |= HotkeyHelper.MOD_SHIFT;
hotkey = hotkey.Replace("Shift", "");
}
GameProvider.HotkeyHelper.RegisterHotKey(this.Handle, hotkeyId, modifIEs, (uint)hotkeyVk);
}
}