在 GTA:SA 中模拟键盘点击

Simulate keyboard click in GTA:SA

我正在尝试 运行 一个有时会模拟 GTA:SA 中的点击的程序。问题是 运行ning 时它什么都不做。到目前为止我已经尝试过这段代码:

IntPtr calculatorHandle = FindWindow(null, "GTA:SA:MP");
if (calculatorHandle == IntPtr.Zero)
{
    MessageBox.Show("GTA:SA:MP isn't running");
    return;
}
SetForegroundWindow(calculatorHandle);
SendKeys.SendWait("T123");

如果您指出我的代码是否有问题,我将非常高兴。谢谢!

编辑

这是我添加 Neill 代码后的代码:

IntPtr calculatorHandle = FindWindow(null, "GTA:SA:MP");
if (calculatorHandle == IntPtr.Zero)
{
    MessageBox.Show("GTA:SA:MP isn't running");
    return;
}
SetForegroundWindow(calculatorHandle);
short key = 0x14;
WindowsMessageService.SendKey(key, KeyFlag.KeyDown);
Thread.Sleep(10);
WindowsMessageService.SendKey(key, KeyFlag.KeyUp);

您的第一个问题是大多数游戏都使用 DirectX 输入。您将必须使用以下方法将密钥发送到游戏。另外,您需要发送上下键来模拟游戏的按键。

[StructLayout(LayoutKind.Sequential)]
struct MouseInput
{
    public int dx;
    public int dy;
    public int mouseData;
    public int dwFlags;
    public int time;
    public IntPtr dwExtraInfo;
}

[StructLayout(LayoutKind.Sequential)]
struct KeyboardInput
{
    public short wVk;      //Virtual KeyCode (not needed here)
    public short wScan;    //Directx Keycode 
    public int dwFlags;    //This tells you what is use (Keyup, Keydown..)
    public int time;
    public IntPtr dwExtraInfo;
}

[StructLayout(LayoutKind.Sequential)]
struct HardwareInput
{
    public int uMsg;
    public short wParamL;
    public short wParamH;
}

[StructLayout(LayoutKind.Explicit)]
struct Input
{
    [FieldOffset(0)]
    public int type;
    [FieldOffset(4)]
    public MouseInput mi;
    [FieldOffset(4)]
    public KeyboardInput ki;
    [FieldOffset(4)]
    public HardwareInput hi;
}

[Flags]
public enum KeyFlag
{       
    KeyDown = 0x0000,
    ExtendedKey = 0x0001,
    KeyUp = 0x0002,
    UniCode = 0x0004,
    ScanCode = 0x0008
}

public static class WindowsMessageService
{
    [DllImport("user32.dll")]
    private static extern UInt32 SendInput(UInt32 nInputs,[MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] Input[] pInputs, Int32 cbSize);

    public static void SendInput(short keycode, KeyFlag keyFlag)
    {
        var inputData = new Input[1];

        inputData[0].type = 1;
        inputData[0].ki.wScan = keycode;
        inputData[0].ki.dwFlags = (int)keyFlag;
        inputData[0].ki.time = 0;
        inputData[0].ki.dwExtraInfo = IntPtr.Zero;

        SendInput(1, inputData, Marshal.SizeOf(typeof(Input)));
    }

    public static void SendKey(short keyCode, KeyFlag keyFlag)
    {
        SendInput(keyCode, keyFlag | KeyFlag.ScanCode);
    }
}

用法示例:

short key = 0x3B; // F1 key

WindowsMessageService.SendKey(key, KeyFlag.KeyDown);

Thread.Sleep(10);

WindowsMessageService.SendKey(key, KeyFlag.KeyUp);