Form1.cs
Private void form1_load (Object sender, system. eventargs E)
{
// Set the hotkey
Sethotkey (false, keys. space );
}
Private bool key_ctrl = false;
Private bool key_shift = false;
Private bool key_alt = false;
Private bool key_windows = false;
Private Keys key_other;
Public void sethotkey (bool bctrl, bool bshift, bool Balt, bool bwindows, keys nowkey)
{
Try
{
This. key_alt = Balt;
This. key_ctrl = bctrl;
This. key_shift = bshift;
This. key_windows = bwindows;
This. key_other = nowkey;
Winhotkey. keymodifiers modifier = winhotkey. keymodifiers. None;
If (this. key_ctrl)
Modifier | = winhotkey. keymodifiers. Control;
If (this. key_alt)
Modifier | = winhotkey. keymodifiers. ALT;
If (this. key_shift)
Modifier | = winhotkey. keymodifiers. shift;
If (this. key_windows)
Modifier | = winhotkey. keymodifiers. windows;
Winhotkey. registerhotkey (handle, 100, modifier, nowkey );
}
Catch
{
MessageBox. Show ("incorrect definition of the shortcut key! ");
}
}
Protected override void wndproc (ref message MSG)
{
Const int wm_hotkey = 0x0312; // hotkey message
If (msg. MSG! = Wm_hotkey)
{
Base. wndproc (ref MSG );
}
Else
{
MessageBox. Show ("hotkey pressed"); // activate the hotkey
// Processhotkey ();
}
}
Private void form1_closing (Object sender, system. componentmodel. canceleventargs E)
{
Winhotkey. unregisterhotkey (handle, 100); // cancel the hotkey
}
Winhotkey. CS
public class winhotkey
{< br> Public winhotkey ()
{< br>
}
[dllimport ("user32.dll", setlasterror = true)]
Public static extern bool registerhotkey (
intptr hwnd,
int ID,
keymodifiers fsmodifiers,
keys VK
);
[dllimport ("user32.dll", setlasterror = true)]
Public static extern bool unregisterhotkey (
intptr hwnd,
int id
);
[Flags ()]
Public Enum keymodifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
}
Download complete source code