102 lines
2.7 KiB
C#
102 lines
2.7 KiB
C#
using System;
|
||
using System.Windows.Forms;
|
||
using static ScreenCapture.NativeMethods;
|
||
|
||
namespace ScreenCapture
|
||
{
|
||
public sealed class KeyboardHook : IDisposable
|
||
{
|
||
private const int WM_HOTKEY = 0x0312;
|
||
|
||
private int _currentId;
|
||
private IntPtr _handle;
|
||
|
||
public KeyboardHook(IntPtr handle)
|
||
{
|
||
_currentId = 0;
|
||
_handle = handle;
|
||
}
|
||
|
||
public void WndProc(ref Message m)
|
||
{
|
||
// check if we got a hot key pressed.
|
||
if (m.Msg == WM_HOTKEY)
|
||
{
|
||
// get the keys.
|
||
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
|
||
ModifierKeysWin modifier = (ModifierKeysWin)((int)m.LParam & 0xFFFF);
|
||
|
||
// invoke the event to notify the parent.
|
||
if (KeyPressed != null)
|
||
KeyPressed(this, new KeyPressedEventArgs(modifier, key));
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Registers a hot key in the system.
|
||
/// </summary>
|
||
/// <param name="modifier">The modifiers that are associated with the hot key.</param>
|
||
/// <param name="key">The key itself that is associated with the hot key.</param>
|
||
public void RegisterHotKey(ModifierKeysWin modifier, Keys key)
|
||
{
|
||
// increment the counter.
|
||
_currentId++;
|
||
|
||
// register the hot key.
|
||
if (!NativeMethods.RegisterHotKey(_handle, _currentId, (uint)modifier, (uint)key))
|
||
throw new InvalidOperationException("Couldn’t register the hot key.");
|
||
}
|
||
|
||
/// <summary>
|
||
/// A hot key has been pressed.
|
||
/// </summary>
|
||
public event EventHandler<KeyPressedEventArgs> KeyPressed;
|
||
|
||
#region IDisposable Members
|
||
|
||
public void Dispose()
|
||
{
|
||
// unregister all the registered hot keys.
|
||
for (int i = _currentId; i > 0; i--)
|
||
{
|
||
UnregisterHotKey(_handle, i);
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
|
||
/// <summary>
|
||
/// Event Args for the event that is fired after the hot key has been pressed.
|
||
/// </summary>
|
||
public class KeyPressedEventArgs : EventArgs
|
||
{
|
||
private ModifierKeysWin _modifier;
|
||
private Keys _key;
|
||
|
||
internal KeyPressedEventArgs(ModifierKeysWin modifier, Keys key)
|
||
{
|
||
_modifier = modifier;
|
||
_key = key;
|
||
}
|
||
|
||
public ModifierKeysWin Modifier
|
||
{
|
||
get { return _modifier; }
|
||
}
|
||
|
||
public Keys Key
|
||
{
|
||
get { return _key; }
|
||
}
|
||
}
|
||
|
||
[Flags]
|
||
public enum ModifierKeysWin : uint
|
||
{
|
||
Alt = 1,
|
||
Control = 2,
|
||
Shift = 4,
|
||
Win = 8
|
||
}
|
||
}
|