Take a form program as an example
public class Form1:form
{
private void Form1_Load (object sender, System.EventArgs e)
{
SetHotKey (False, False, False, true, Keys.right, 100); Set multiple hotkeys
SetHotKey (False, False, False, True, Keys.space, 101);
SetHotKey (False, False, False, True, Keys.up, 102);
SetHotKey (False, False, False, True, Keys.down, 103);
}
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,int)
{
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,keyid,modifier,nowkey);
}
Catch
{
MessageBox.Show ("Shortcut key definition Error!) ");
}
}
protected override void WndProc (ref message MSG)
{
const int wm_hotkey = 0x0312; Hot Key Message
if (Msg. MSG!= Wm_hotkey)
{
Base. WndProc (ref msg);
}
Else
{
Activates the hotkey, where you can add a handler
if (= = = (int) msg. WParam)
{
DoSomething
}
else if (int) msg. WParam)
{
DoSomething
}
else if (102 = = (int) msg. WParam)
{
DoSomething
}
Else
{
DoSomething
}
}
}
private void Form1_Closing (object sender, System.ComponentModel.CancelEventArgs e)
{
Winhotkey.unregisterhotkey (Handle); /Logoff hotkey
Winhotkey.unregisterhotkey (Handle,; ) /Logoff Hotkey
Winhotkey.unregisterhotkey (Handle, 102); //Logoff hotkey
Winhotkey.unregisterhotkey ( Handle,; /Logoff hotkey
}
Public class Winhotkey
{
public Winhotkey ()
{
}
[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
}
}
This completes the definition of the hotkey