鍵盤鉤子
環(huán)境win10 打包參數(shù) IL2CPP 2018.2.0f2 Windows X86 .NET 4.x
放到Unity里注意當(dāng)unity失去焦點時 應(yīng)取消鍵盤鉤子 否則在程序外也會生效
using UnityEngine;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class MonoPInvokeCallbackAttribute : Attribute
{
public MonoPInvokeCallbackAttribute() { }
}
public class WindowsKeyTool : MonoBehaviour
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static int _hookID;
public static bool KeyOn = true;
void Start()
{
UnhookWindowsHookEx((IntPtr)_hookID);
_hookID = SetHook(_proc);
}
void OnApplicationQuit()
{
UnhookWindowsHookEx((IntPtr)_hookID);
}
private void OnDestroy()
{
UnhookWindowsHookEx((IntPtr)_hookID);
}
private static int SetHook(LowLevelKeyboardProc proc)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, IntPtr.Zero, 0);
}
private delegate int LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
//return 1 代表攔截
[MonoPInvokeCallback]
private static int HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
//wParam == 256 代表 按下操作 257 代表抬起操作
int vkCode = Marshal.ReadInt32(lParam);
bool isKeyDown = ((int)wParam == WM_KEYDOWN);
if (vkCode == 0x41)//如果按下A 截斷 重新按下 新的按鍵
{
if (isKeyDown)
{
keybd_event(91, 0, 0, 0);
return 1;
}
else
{
keybd_event(91, 0, 2, 0);
return 1;
}
}
return CallNextHookEx((IntPtr)_hookID, nCode, wParam, lParam);//不攔截將按鍵消息傳遞給下個鉤子
}
[DllImport("user32.dll")] // 注意下面這三個函數(shù)和其他網(wǎng)上找到的 不一樣 我把一些 IntPtr 參數(shù)以及返回值 改成了 int (不改 編輯器以及mono打包是沒問題的)
//不改的話 il2cpp 會說參數(shù)C錯誤 不知道為什么 希望知道的大神告知 學(xué)習(xí)學(xué)習(xí)
private static extern int SetWindowsHookEx(int idHook,LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll")]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
private static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
/// <summary>
///
/// 模擬按鍵按下抬起
///
/// keybd_event((byte)65, 0, 0, 0); 按下F10
/// keybd_event((byte)65, 0, 2, 0); 按下后松開F10
///
/// </summary>
/// <param name="bVk"></param>
/// <param name="bScan"></param>
/// <param name="dwFlags">0為按下 2為釋放</param>
/// <param name="dwExtraInfo"></param>
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
}
鍵值表 https://blog.csdn.net/tonykk2008/article/details/8264967
不支持Unity2021