按键拦截改变继续传递

可以不放到 unity中使用

using UnityEngine;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

/// 
/// 拦截 键值为 172 的按键 转换成 72 H键
/// 
public class WindowsKeyTool : MonoBehaviour
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;
    public static bool KeyOn = true;

    void Start()
    {
        _hookID = SetHook(_proc);
        UnityEngine.Debug.Log("Start InterceptKeys!!");
    }

    void OnApplicationQuit()
    {
        UnhookWindowsHookEx(_hookID);
    }

    private void OnDestroy()
    {
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

    //这个函数return 1 代表拦截 当前的按键 目前 
    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        //wParam == 256 代表 按下操作 257 代表抬起操作
        int vkCode = Marshal.ReadInt32(lParam);
        bool isKeyDown = (int)wParam == 256;

        if (vkCode == 172)
        {
            if (isKeyDown)
            {
                keybd_event((byte)72, 0, 0, 0); //按下 72 H键
                return (IntPtr)1;
            }
            else
            {
                keybd_event((byte)72, 0, 2, 0); //按下后松开  H键
                return (IntPtr)1;
            }
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);


    /// 
    /// 
    /// 模拟按键按下抬起
    /// 
    /// keybd_event((byte)65, 0, 0, 0);   按下F10
    /// keybd_event((byte)65, 0, 2, 0);   按下后松开F10
    /// 
    /// 
    /// 
    /// 
    /// 0为按下 2为释放
    /// 
    [DllImport("user32.dll")]
    public static extern void keybd_event(
       byte bVk,
       byte bScan,
       int dwFlags,     //这里为整数类型 0为按下,2为释放
       int dwExtraInfo
   );
}

你可能感兴趣的:(按键拦截改变继续传递)