I’m trying to block the Windows key input in my Unity game using SetWindowsHookEx. While this approach works perfectly in a standard C# application, it’s not functioning as expected in Unity.
Here’s my current implementation:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
public static class NativeKeyBlocker
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101;
private const int WM_SYSKEYDOWN = 0x0104;
private const int WM_SYSKEYUP = 0x0105;
private const int VK_LWIN = 0x5B;
private const int VK_RWIN = 0x5C;
private static IntPtr _hookID = IntPtr.Zero;
public static void BlockWinKey()
{
if (_hookID == IntPtr.Zero)
{
_hookID = SetHook(HookCallback);
}
}
public static void UnblockWinKey()
{
if (_hookID != IntPtr.Zero)
{
UnhookWindowsHookEx(_hookID);
_hookID = IntPtr.Zero;
}
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, IntPtr.Zero, 0);
/* Working same as above line.
using (var curProcess = Process.GetCurrentProcess())
{
using (var curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
*/
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 &&
(wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN
|| wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP))
{
int vkCode = Marshal.ReadInt32(lParam);
UnityEngine.Debug.LogError($"Key: {vkCode} event: {wParam}");
if (vkCode == VK_LWIN || vkCode == VK_RWIN)
{
return (IntPtr)1; // Block the key
}
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
}
Current behavior:
- When Unity has focus (in editor or player):
- HookCallback is not being called
- Windows key still opens the Start menu
- Game loses focus
- When Unity loses focus:
- HookCallback works properly
- Windows key is blocked as intended
I’ve tried both approaches for setting up the hook:
- Direct SetWindowsHookEx call
- Using GetModuleHandle with the current process
The same code works flawlessly in a regular C# application, which suggests this might be Unity-specific. What could be causing this behavior in Unity, and what’s the proper way to block specific key inputs in this context?