How to make a hotkey for your program? For example, pressing CTRL + A will trigger an event of your program?
Usage:
Code
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
btnTest_Click(this, EventArgs.Empty);
}
}
The method is simple and effective! But have you found a problem? That is, when the program loses focus, this hot key (shortcut key) will not work! What should we do? In fact, the solution also
Yes! We need to use WIN32API again. I do not need to explain the meanings of the two functions registerhotkey and unregisterhotkey! Look at the surface
Now you know the registration and logout hotkeys.
Code
Public class hotkey // if the function is successfully executed, the return value is not 0. // If the function fails to be executed, the return value is 0. To get the extended error message, call getlasterror.
{
[Dllimportattribute ("user32.dll", entrypoint = "registerhotkey")]
Public static extern bool registerhotkey
(
Intptr hwnd, // The Window handle to register the hotkey
Int ID, // hotkey ID defines the hotkey ID (cannot be the same as other IDS)
Int fsmodifiers, // special keys such as Ctrl, ALT, shift, window // identify whether the hot keys take effect only when pressing ALT, Ctrl, shift, windows, and other keys
Int VK // General keys such as a B C F1, F2, and so on.
);
[Dllimportattribute ("user32.dll", entrypoint = "unregisterhotkey")]
Public static extern bool unregisterhotkey
(
Intptr hwnd, // handle of the window to which the hotkey is to be canceled
Int ID // the ID of the hotkey to be canceled
);
[Flags ()] // after attaching the flags feature, you can use this enumerated variable to perform bitwise "|" or bitwise "&" operations like integers.
Public Enum mykeys
{
None = 0,
Alt = 1,
CTRL = 2,
Shift = 4,
Win = 8
}
Public const int wm_hotkey = 0x312;
}
The hotkeys registered with registerhotkey can also be valid when the focus is lost!
All the implementation code is as follows:
Using system. runtime. interopservices;
Code
Private void form1_load (Object sender, eventargs E)
{
Hotkey. registerhotkey (this. Handle, 200, (INT) hotkey. mykeys. ALT, (INT) keys. a); // register the hot key Alt +
// Hotkey. registerhotkey (this. handle, 200, (INT) hotkey. mykeys. CTRL | (INT) hotkey. mykeys. ALT, (INT) keys. a); // register the hot key CTRL + ALT +
// Hotkey. registerhotkey (this. Handle, 200, (INT) hotkey. mykeys. None, (INT) keys. F2); // register the hotkey F2
}
Private void form=formclosing (Object sender, formclosingeventargs E)
{
Hotkey. unregisterhotkey (this. Handle, 200); // cancel the hotkey.
}
Private void btntest_click (Object sender, eventargs E)
{
MessageBox. Show ("btntest click event triggered! ");
}
Protected override void wndproc (ref message m)
{
If (M. MSG = hotkey. wm_hotkey)
{
Switch (M. wparam. toint32 ())
{
Case 200:
Btntest_click (this, eventargs. Empty );
Break;
}
}
Base. wndproc (ref m );
}