this is easy. don't need to unregister it.
Code:
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
namespace class
{
public class HotKey
{
private static Hashtable KeyPair = new Hashtable();
private IntPtr Handle;
private Window window;
private uint Controlkey;
private uint Key;
private const int WM_HOTKEY = 786;
public int KeyId { set; get; }
public event HotKey.OnHotkeyEventHandeler OnHotKey;
public void Regist(Window win, HotKey.KeyFlags control, Keys key)
{
Handle = new WindowInteropHelper(win).Handle;
window = win;
Controlkey = (uint)control;
Key = (uint)key;
KeyId = (int)Controlkey + (int)Key * 10;
if (HotKey.KeyPair.ContainsKey((object)KeyId))
throw new Exception("Error happened HOTKEY 0x12");
if (!HotKey.RegisterHotKey(Handle, KeyId, Controlkey, Key))
throw new Exception("Error happened HOTKEY 0x13");
if (HotKey.KeyPair.Count == 0 && !HotKey.InstallHotKeyHook(this))
throw new Exception("Error happened HOTKEY 0x12");
HotKey.KeyPair.Add((object)KeyId, (object)this);
}
public void UnRegist(Window win, int KeyId)
{
HotKey.UnregisterHotKey(new WindowInteropHelper(win).Handle, KeyId);
}
[DllImport("user32")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint controlKey, uint virtualKey);
[DllImport("user32")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private static bool InstallHotKeyHook(HotKey hk)
{
if (hk.window == null || hk.Handle == IntPtr.Zero)
return false;
HwndSource hwndSource = HwndSource.FromHwnd(hk.Handle);
if (hwndSource == null)
return false;
hwndSource.AddHook(new HwndSourceHook(HotKey.HotKeyHook));
return true;
}
private static IntPtr HotKeyHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 786)
{
HotKey hotKey = (HotKey)HotKey.KeyPair[(object)(int)wParam];
// ISSUE: reference to a compiler-generated field
if (hotKey.OnHotKey != null)
{
// ISSUE: reference to a compiler-generated field
hotKey.OnHotKey();
}
}
return IntPtr.Zero;
}
~HotKey()
{
HotKey.UnregisterHotKey(this.Handle, this.KeyId);
}
public delegate void OnHotkeyEventHandeler();
public enum KeyFlags
{
Mod_None = 0,
MOD_ALT = 1,
MOD_CONTROL = 2,
MOD_CONTROLALT = 3,
MOD_SHIFT = 4,
MOD_WIN = 8,
}
}
}
use it like that on form loaded():
Code:
try {
HotKey hotKey = new HotKey();
hotKey.Regist((Window)this, HotKey.KeyFlags.Mod_None, Keys.F9);
hotKey.OnHotKey += new HotKey.OnHotkeyEventHandeler(your_function);
} catch { //error }