This repository has been archived on 2017-12-27. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
ScreenCapture/KeyboardHook.cs
2015-09-27 12:13:23 +02:00

102 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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("Couldnt 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
}
}