Flow.Launcher/Flow.Launcher.Infrastructure/Hotkey/GlobalHotkey.cs

94 lines
2.8 KiB
C#
Raw Permalink Normal View History

2014-03-18 16:26:09 +00:00
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Plugin;
2014-03-18 16:26:09 +00:00
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.Infrastructure.Hotkey
2014-03-18 16:26:09 +00:00
{
/// <summary>
/// Listens keyboard globally.
/// <remarks>Uses WH_KEYBOARD_LL.</remarks>
/// </summary>
2021-12-06 00:22:41 +00:00
public unsafe class GlobalHotkey : IDisposable
2014-03-18 16:26:09 +00:00
{
private static readonly IntPtr hookId;
2014-03-18 16:26:09 +00:00
public delegate bool KeyboardCallback(KeyEvent keyEvent, int vkCode, SpecialKeyState state);
internal static Func<KeyEvent, int, SpecialKeyState, bool> hookedKeyboardCallback;
2014-03-18 16:26:09 +00:00
//Modifier key constants
private const int VK_SHIFT = 0x10;
private const int VK_CONTROL = 0x11;
private const int VK_ALT = 0x12;
private const int VK_WIN = 91;
static GlobalHotkey()
{
2014-03-18 16:26:09 +00:00
// Set the hook
hookId = InterceptKeys.SetHook(& LowLevelKeyboardProc);
2014-03-18 16:26:09 +00:00
}
public static SpecialKeyState CheckModifiers()
2014-03-18 16:26:09 +00:00
{
SpecialKeyState state = new SpecialKeyState();
if ((InterceptKeys.GetKeyState(VK_SHIFT) & 0x8000) != 0)
{
//SHIFT is pressed
state.ShiftPressed = true;
}
if ((InterceptKeys.GetKeyState(VK_CONTROL) & 0x8000) != 0)
{
//CONTROL is pressed
state.CtrlPressed = true;
}
if ((InterceptKeys.GetKeyState(VK_ALT) & 0x8000) != 0)
{
//ALT is pressed
state.AltPressed = true;
}
if ((InterceptKeys.GetKeyState(VK_WIN) & 0x8000) != 0)
{
2016-01-22 12:47:00 +00:00
//WIN is pressed
2014-03-18 16:26:09 +00:00
state.WinPressed = true;
}
return state;
}
2021-12-06 03:49:09 +00:00
[UnmanagedCallersOnly]
private static IntPtr LowLevelKeyboardProc(int nCode, UIntPtr wParam, IntPtr lParam)
2014-03-18 16:26:09 +00:00
{
bool continues = true;
if (nCode >= 0)
{
if (wParam.ToUInt32() == (int)KeyEvent.WM_KEYDOWN ||
wParam.ToUInt32() == (int)KeyEvent.WM_KEYUP ||
wParam.ToUInt32() == (int)KeyEvent.WM_SYSKEYDOWN ||
wParam.ToUInt32() == (int)KeyEvent.WM_SYSKEYUP)
{
if (hookedKeyboardCallback != null)
continues = hookedKeyboardCallback((KeyEvent)wParam.ToUInt32(), Marshal.ReadInt32(lParam), CheckModifiers());
}
}
if (continues)
{
return InterceptKeys.CallNextHookEx(hookId, nCode, wParam, lParam);
}
return (IntPtr)(-1);
2014-03-18 16:26:09 +00:00
}
2021-12-06 00:22:41 +00:00
public void Dispose()
2014-03-18 16:26:09 +00:00
{
InterceptKeys.UnhookWindowsHookEx(hookId);
}
2021-12-06 00:22:41 +00:00
~GlobalHotkey()
{
Dispose();
}
2014-03-18 16:26:09 +00:00
}
}