Skip to content

Instantly share code, notes, and snippets.

@peppy
Created June 25, 2020 11:03
Show Gist options
  • Save peppy/4295b25edb715fe37ae690367ab5c428 to your computer and use it in GitHub Desktop.
Save peppy/4295b25edb715fe37ae690367ab5c428 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace osu.Helpers
{
class WindowsKey
{
private delegate int LowLevelKeyboardProcDelegate(int nCode, int wParam, ref KBDLLHOOKSTRUCT lParam);
internal static bool IsBlocked;
[DllImport(@"user32.dll", EntryPoint = @"SetWindowsHookExA", CharSet = CharSet.Ansi)]
private static extern int SetWindowsHookEx(int idHook, LowLevelKeyboardProcDelegate lpfn, IntPtr hMod, int dwThreadId);
[DllImport(@"user32.dll")]
private static extern int UnhookWindowsHookEx(int hHook);
[DllImport(@"user32.dll", EntryPoint = @"CallNextHookEx", CharSet = CharSet.Ansi)]
private static extern int CallNextHookEx(int hHook, int nCode, int wParam, ref KBDLLHOOKSTRUCT lParam);
const int WH_KEYBOARD = 2;
const int WH_KEYBOARD_LL = 13;
private static int keyHook;
private KBDLLHOOKSTRUCT lParam;
private struct KBDLLHOOKSTRUCT
{
public int vkCode;
int scanCode;
public int flags;
int time;
int dwExtraInfo;
}
private static int lowLevelKeyboardProc(int nCode, int wParam, ref KBDLLHOOKSTRUCT lParam)
{
switch (wParam)
{
case 256:
case 257:
case 260:
case 261:
//Alt+Tab, Alt+Esc, Ctrl+Esc, Windows Key
if ((lParam.vkCode == 91 || lParam.vkCode == 92) && lParam.flags == 1)
return 1;
break;
}
return CallNextHookEx(0, nCode, wParam, ref lParam);
}
static LowLevelKeyboardProcDelegate del;
internal static void Disable()
{
if (keyHook != 0 || IsBlocked)
return;
try
{
keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (del = lowLevelKeyboardProc), Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]), 0);
}
catch { }
IsBlocked = true;
}
internal static void Enable()
{
if (keyHook == 0 || !IsBlocked)
return;
try
{
keyHook = UnhookWindowsHookEx(keyHook);
del = null;
}
catch { }
keyHook = 0;
IsBlocked = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment