Dan Amiga who is a great co-worker and a very tallent person showed me a very cool shortcuts application (C++) he wrote. I was so amazed about how easy it is to access any applications with few key strokes that I went home and wrote my own implementation for the same applciation, in C# of course.
The #1 thing I did was to implement this Component which fires a HotKeyPressed event when a desired windows HotKey was pressed.
Here is the implementation :
UPDATE: There was a mistake with the intptr Handle. Notice that now you need to supply the Form.Handle to this component. Suspend, Shutdown and Restart will work properly now...
public
class HotKey : Component , IMessageFilter
{
public event EventHandler HotKeyPressed;
private const int id = 100;
#region
Native win32 API
private const int WM_HOTKEY = 0x0312;
[
DllImport("user32.dll", SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);
[
DllImport("user32.dll", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[
Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
#endregion
public event EventHandler KeyChanged;
public event EventHandler KeyModifierChanged;
private IntPtr handle;
public IntPtr Handle
{
get { return handle; }
set { handle = value; }
}
private Keys key;
private KeyModifiers keyModifier;
private bool isKeyRegisterd;
public HotKey()
{
Application.AddMessageFilter(
this);
}
~HotKey()
{
Application.RemoveMessageFilter(
this);
UnregisterHotKey(handle, id);
}
private void RegisterHotKey()
{
if (key == Keys.None)
return;
if (isKeyRegisterd)
isKeyRegisterd = !(UnregisterHotKey(handle, id));
isKeyRegisterd = RegisterHotKey(handle, id, keyModifier, key);
if (!isKeyRegisterd)
throw new ApplicationException("Hotkey allready in use");
}
[Bindable(
true), Category("HotKey")]
public Keys Key
{
get { return key; }
set
{
if (key != value)
{
key =
value;
OnKeyChanged(
new EventArgs());
}
}
}
[Bindable(
true), Category("HotKey")]
public KeyModifiers KeyModifier
{
get { return keyModifier; }
set
{
if (keyModifier != value)
{
keyModifier =
value;
OnKeyModifierChanged(
new EventArgs());
}
}
}
public bool PreFilterMessage(ref Message m)
{
switch (m.Msg)
{
case WM_HOTKEY:
OnHotKeyPressed(
new EventArgs());
return true;
}
return false;
}
private void OnHotKeyPressed(EventArgs e)
{
if (HotKeyPressed != null)
HotKeyPressed(
this, e);
}
private void OnKeyChanged(EventArgs e)
{
RegisterHotKey();
if (KeyChanged != null)
KeyChanged(
this, e);
}
private void OnKeyModifierChanged(EventArgs e)
{
RegisterHotKey();
if (KeyModifierChanged != null)
KeyModifierChanged(
this, e);
}
}