Originally heard WINAPI inside the registerhotkey sometimes not good, and then intend to use the Hook keyboard message to do hook key, found the hook there to deal with the message there is very troublesome, also think will cause the system of extra overhead is relatively large, So finally with RegisterHotKey to encapsulate a bit, the test is no problem, or can be. (WinForm)
The following code includes the processing of a textbox and a class that encapsulates the API. TextBox there is to deal with user-defined hotkey interface, such as the user button will appear "Ctrl+alt+a" and so on, API encapsulation where do the processing, just register well, do not pipe unregister, when registering a similar ID hotkey , will automatically first unregister the original, and then finally close the window, call Hotkeyhelper.dispose () on it. I also hope to add more suggestions. Here we go..
----------------------- ---------------------------------------------------------
Textbox section: (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 = "None";
}
}
private void Btnhotkey_click (object sender, EventArgs e)
{
String hotkey = TxbHotKey.Text.Replace ("+", "");
if (Hotkey!= "None" && 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);
}
}