In my form, I register different Hotkeys. Later during execution, I would like to know which of the Hotkeys was actually pressed. Where can I get that information from?
Registering during Initialization:
public Form1()
{
this.KeyPreview = true;
ghk = new KeyHandler(Keys.F1, this);
ghk.Register();
ghk = new KeyHandler(Keys.F2, this);
ghk.Register();
InitializeComponent();
}
Using this KeyHandler Class:
public class KeyHandler
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private int key;
private IntPtr hWnd;
private int id;
public KeyHandler(Keys key, Form form)
{
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}
public override int GetHashCode()
{
return key ^ hWnd.ToInt32();
}
public bool Register()
{
return RegisterHotKey(hWnd, id, 0, key);
}
public bool Unregister()
{
return UnregisterHotKey(hWnd, id);
}
}
The method that is triggered:
protected override void WndProc(ref Message m)
{
if (m.Msg == Constants.WmHotkeyMsgId)
HandleHotkey(m);
base.WndProc(ref m);
}
Here I want to distinguish between two Hotkeys:
private void HandleHotkey(Message m)
{
if(key == F1)
DoSomething
if(key == F2)
DoSomethingElse
}