[Release]HotKeyForm
Just decided to whip this up earlier today. Basically, this is a windows Form extension class with inbuilt global hotkey support. I've tested it only minimally so I welcome bug reports and the like.
Add the class to your project (Project >> Add Class) using the provided source code. Next, go to the form you desire to have hotkeys. In the code you should see something like
Instead, change it to the following:
Now all that remains to do is Add/Remove hotkeys and define your callback. The callback must match the "HotkeyCallback" delegate's signature. The following is an example of such a callback:
Now to add a hotkey is super simple. You need three things:
1. Virtual Keycode: a full list can be found here, but for the most part you can simple cast a member of the "Keys" enum to a uint for this parameter (both methods shown below)
2. KeyModifier: Pretty simple, pick the modifier you'd like to go with the key (i.e for a Shift+A hotkey, the Virtual Keycode would be for the letter 'A' and the KeyModifier parameter would be KeyModifier.Shift). Leave this as KeyModifier.None if you don't want a modifier.
3. Callback We've already done this in the above step.
Now, to add a hotkey for the "A" key by itself:
And if you wanted to add a "Shift+S" hotkey:
To remove a hotkey again, just call RemoveHotKey with the same values for VirtualKeyCode and KeyModifier.
And, the code:
Private Paste - Pastie
Enjoy, post feedback/bugs below.
Cheers.
Add the class to your project (Project >> Add Class) using the provided source code. Next, go to the form you desire to have hotkeys. In the code you should see something like
Code:
public class Form1 : Form
Code:
public class Form1 : HotKeyForm
Code:
private void HotkeyCallback(uint vkCode, KeyModifier modifier)
{
MessageBox.Show(string.Format("The '{0}' key was pressed! (Modifier: {1})", (Keys)vkCode, modifier));
}
1. Virtual Keycode: a full list can be found here, but for the most part you can simple cast a member of the "Keys" enum to a uint for this parameter (both methods shown below)
2. KeyModifier: Pretty simple, pick the modifier you'd like to go with the key (i.e for a Shift+A hotkey, the Virtual Keycode would be for the letter 'A' and the KeyModifier parameter would be KeyModifier.Shift). Leave this as KeyModifier.None if you don't want a modifier.
3. Callback We've already done this in the above step.
Now, to add a hotkey for the "A" key by itself:
Code:
// both of the following are equivalent AddHotKey(0x41, KeyModifier.None, HotkeyCallback); AddHotKey((uint)Keys.A, KeyModifier.None, HotkeyCallback);
Code:
// both of the following are equivalent AddHotKey(0x53, KeyModifier.Shift, HotkeyCallback); AddHotKey((uint)Keys.S, KeyModifier.Shift, HotkeyCallback);
Code:
RemoveHotKey((uint)Keys.A, KeyModifier.None);
Private Paste - Pastie
Code:
public class HotKeyForm : Form
{
// Method signature for hotkey callbacks
protected delegate void HotKeyCallback(uint key, KeyModifier modifier);
// Map hotkey masks to their callback information
private Dictionary<int, HotKeyInfo> _hotkeys = new Dictionary<int, HotKeyInfo>();
// Random number provider
private static Random RND_PROVIDER = new Random();
public HotKeyForm()
: base()
{ }
/// <summary>
/// Custom message queue handler, overridden to specifically handle the WM_HOTKEY message, all messages are forwarded to Form.WndProc(...)
/// </summary>
/// <param name="m">Message information about the current message</param>
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312) // WM_HOTKEY
{
int mask = m.LParam.ToInt32(); // HIWORD is the virtual key code, LOWORD is any modifiers.
if (_hotkeys.ContainsKey(mask)) // Is this one of our registered hotkeys?
{
// Unmask the hotkey into it's component parts, then run all the callbacks tied to this particular key combination
var hotkey = _hotkeys[mask];
KeyModifier mod;
uint vk;
UnmaskHotKey(mask, out vk, out mod);
hotkey.RunCallbacks(vk, mod);
}
}
base.WndProc(ref m);
}
/// <summary>
/// Add a new callback for a hotkey
/// </summary>
/// <param name="virtualKey">Virtual keycode of the hotkey to add</param>
/// <param name="modifiers">Modifiers (if any) applied to the hotkey</param>
/// <param name="callback">Callback function to execute when the HotKey is pressed</param>
/// <returns>True if the callback was successfully registered for the HotKey, false otherwise</returns>
protected bool AddHotKey(uint virtualKey, KeyModifier modifiers, HotKeyCallback callback)
{
// Sanity check
if (callback != null && Array.IndexOf(Enum.GetValues(typeof(KeyModifier)), modifiers) != -1)
{
int mask = MaskHotKey(virtualKey, modifiers);
// Check if this key combo is already registered
if (_hotkeys.ContainsKey(mask))
{
// just add the new callback
_hotkeys[mask].RegisterCallback(callback);
return true;
}
else
{
// Use random ids in the allowable range to try and find a usable HWND/Id combination
int id = RND_PROVIDER.Next(0, 0xBFFF);
bool registered = false;
// Keep changing the id until an available one is found, or until the last error isn't HOTKEY_ALREADY_REGISTERED
while (IsRegisteredId(id) || (!(registered = RegisterHotKey(Handle, id, (uint)modifiers, virtualKey)) && Marshal.GetLastWin32Error() == 1409))
id = RND_PROVIDER.Next(0, 0xBFFF);
if (registered)
{
_hotkeys.Add(mask, new HotKeyInfo( id ));
return true;
}
}
}
return false;
}
/// <summary>
/// Remove a registered hotkey and all of its callbacks
/// </summary>
/// <param name="virtualKey">Virtual keycode of the hotkey to remove</param>
/// <param name="modifiers">Modifiers (if any) applied to the hotkey</param>
/// <returns>True if the hotkey is no longer registered, false otherwise</returns>
protected bool RemoveHotKey(uint virtualKey, KeyModifier modifiers)
{
int mask = MaskHotKey(virtualKey, modifiers);
return !_hotkeys.ContainsKey(mask) || (UnregisterHotKey(Handle, _hotkeys[mask].Id) && _hotkeys.Remove(mask));
}
// Check if the id provided in the "id" parameter is already assigned to a local hotkey.
// RegisterHotkey allows a unique Hwnd to use the same id multiple times, but this makes it impossible to differentiate
// between registered hotkeys and to unregister them individually. Thus, the short helper function to check internally for the use
// of a given id.
private bool IsRegisteredId(int id)
{
foreach (var val in _hotkeys.Values)
if (val.Id == id)
return true;
return false;
}
// Mask the component parts of a HotKey into a single DWORD
private static int MaskHotKey(uint key, KeyModifier modifiers)
{
return (int)(((key & 0xFFFF) << 16) + ((int)modifiers & 0xFFFF));
}
// Unmask the component parts of a hotkey from a single DWORD.
private static void UnmaskHotKey(int mask, out uint key, out KeyModifier modifiers)
{
key = (uint)((mask >> 16) & 0xFFFF);
modifiers = (KeyModifier)(mask & 0xFFFF);
}
// Special key modifiers
protected enum KeyModifier
{
None = 0x0000,
Alt = 0x0001,
Control = 0x0002,
Shift = 0x0004,
Windows = 0x0008
};
// Small utility class to hold and manipulate basic information about a hotkey
private class HotKeyInfo
{
public int Id { get; private set; }
private List<HotKeyCallback> _callbacks = new List<HotKeyCallback>();
public HotKeyInfo(int id) { Id = id; }
public void RunCallbacks(uint vk, KeyModifier m)
{
foreach (var callback in _callbacks)
callback(vk, m);
}
public void RegisterCallback(HotKeyCallback callback)
{
if (callback != null && !_callbacks.Contains(callback))
_callbacks.Add(callback);
}
};
// WinAPI definitions
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
}
Cheers.

![=]](/forum/images/emotions/=].gif)