Bitte beachten Sie, dass dieser Code keine Ereignisse in Konsolenanwendungsprojekten auslöst . Sie müssen das WinForms-Projekt verwenden, damit Ereignisse ausgelöst werden.
Dies ist der richtige Code:
public sealed class KeyboardHook : IDisposable
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private class Window : NativeWindow, IDisposable
{
private static int WM_HOTKEY = 0x0312;
public Window()
{
this.CreateHandle(new CreateParams());
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_HOTKEY)
{
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);
if (KeyPressed != null)
KeyPressed(this, new KeyPressedEventArgs(modifier, key));
}
}
public event EventHandler<KeyPressedEventArgs> KeyPressed;
#region IDisposable Members
public void Dispose()
{
this.DestroyHandle();
}
#endregion
}
private Window _window = new Window();
private int _currentId;
public KeyboardHook()
{
_window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
{
if (KeyPressed != null)
KeyPressed(this, args);
};
}
public void RegisterHotKey(ModifierKeys modifier, Keys key)
{
_currentId = _currentId + 1;
if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
throw new InvalidOperationException("Couldn’t register the hot key.");
}
public event EventHandler<KeyPressedEventArgs> KeyPressed;
#region IDisposable Members
public void Dispose()
{
for (int i = _currentId; i > 0; i--)
{
UnregisterHotKey(_window.Handle, i);
}
_window.Dispose();
}
#endregion
}
public class KeyPressedEventArgs : EventArgs
{
private ModifierKeys _modifier;
private Keys _key;
internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
{
_modifier = modifier;
_key = key;
}
public ModifierKeys Modifier
{
get { return _modifier; }
}
public Keys Key
{
get { return _key; }
}
}
[Flags]
public enum ModifierKeys : uint
{
Alt = 1,
Control = 2,
Shift = 4,
Win = 8
}
zu verwenden (ich musste die Modifikatortasten bearbeiten, um sie zu wirken (Modifikator) 1 (Modifikator) 2 usw.
public partial class Form1 : Form
{
KeyboardHook hook = new KeyboardHook();
public Form1()
{
InitializeComponent();
hook.KeyPressed +=
new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);
hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt,
Keys.F12);
}
void hook_KeyPressed(object sender, KeyPressedEventArgs e)
{
label1.Text = e.Modifier.ToString() + " + " + e.Key.ToString();
}
}