You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Unity新输入系统发送可识别的键盘按键模拟事件?

Unity新输入系统下跨应用模拟键盘事件的解决方案

1. 替换keybd_event为SendInput

keybd_event是Windows已废弃的API,Unity新输入系统对其模拟的事件捕获支持有限,改用SendInput可以更可靠地生成系统级键盘事件,能被新输入系统识别:

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

public class CrossAppKeyboardSimulator : MonoBehaviour
{
    [StructLayout(LayoutKind.Sequential)]
    private struct INPUT
    {
        public int type;
        public InputUnion u;
    }

    [StructLayout(LayoutKind.Explicit)]
    private struct InputUnion
    {
        [FieldOffset(0)] public KEYBDINPUT ki;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct KEYBDINPUT
    {
        public ushort wVk;
        public ushort wScan;
        public uint dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }

    private const int INPUT_KEYBOARD = 1;
    private const uint KEYEVENTF_KEYDOWN = 0x0000;
    private const uint KEYEVENTF_KEYUP = 0x0002;

    [DllImport("user32.dll", SetLastError = true)]
    private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);

    public void SimulateEnter()
    {
        SimulateKeyPress((ushort)KeyCode.Return);
    }

    private void SimulateKeyPress(ushort virtualKeyCode)
    {
        var inputs = new INPUT[2];

        // 按下事件
        inputs[0].type = INPUT_KEYBOARD;
        inputs[0].u.ki.wVk = virtualKeyCode;
        inputs[0].u.ki.dwFlags = KEYEVENTF_KEYDOWN;

        // 释放事件
        inputs[1].type = INPUT_KEYBOARD;
        inputs[1].u.ki.wVk = virtualKeyCode;
        inputs[1].u.ki.dwFlags = KEYEVENTF_KEYUP;

        SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
    }
}

2. 同进程内直接模拟新输入系统事件

如果两个Unity应用运行在同一进程(或你可以修改目标应用的代码),可以跳过系统级模拟,直接通过新输入系统API注入事件:

using UnityEngine.InputSystem;

public class InProcessInputSimulator : MonoBehaviour
{
    public void SimulateEnter()
    {
        Keyboard.current.returnKey.Press();
        // 短延迟确保输入事件被正确处理
        Invoke(nameof(ReleaseEnterKey), 0.05f);
    }

    private void ReleaseEnterKey()
    {
        Keyboard.current.returnKey.Release();
    }
}

3. 检查目标应用的新输入系统配置

确保目标应用的新输入系统启用了必要的支持:

  • 打开Edit > Project Settings > Input System Package
  • 勾选Enable Native Platform Backends
  • Windows平台下,可尝试启用Allow Windows Virtual Keys来优化虚拟输入的识别

内容的提问来源于stack exchange,提问作者yogesh sriraman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 15:25:07