我需要一些关于DirectInput的帮助,我会告诉我想要做什么。当我只按一个键时,我想让我的程序向游戏发送键组合。例子:我将按“r”,它将按“1”,“3”,“2”,“4”键。我从这里找到了一些代码。但他们并没有完全奏效。
public static void Send_Key_Hold(short Keycode)
{
INPUT[] InputData = new INPUT[1];
InputData[0].type = 1;
InputData[0].ki.wScan = Keycode;
InputData[0].ki.dwFlags = (int)(KEYEVENTF_SCANCODE);
SendInput(1, InputData, Marshal.SizeOf(InputData[0]));
}
public static void Send_Key_Release(short Keycode)
{
INPUT[] InputData = new INPUT[1];
InputData[0].type = 1;
InputData[0].ki.wScan = Keycode;
InputData[0].ki.dwFlags = (int)(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE);
SendInput(1, InputData, Marshal.SizeOf(InputData[0]));
}
这是我的代码和我的问题:当我使用Send_Key_Hold时,它只按下游戏中的一个键并且没有按下其他组合键,因为我认为第一个键是持久的。当我一起使用Send_Key_Hold和Send_Key_Release时,它不会按下游戏上的任何按钮。但是在桌面上(我的意思是任何其他应用程序而不是游戏)它按下键。
答案 0 :(得分:5)
我在互联网上找到了这个例子。当我尝试做你现在尝试的同样的事情时,我自己进行了测试。
[Flags]
private enum InputType
{
Mouse = 0,
Keyboard = 1,
Hardware = 2
}
[Flags]
private enum KeyEventF
{
KeyDown = 0x0000,
ExtendedKey = 0x0001,
KeyUp = 0x0002,
Unicode = 0x0004,
Scancode = 0x0008,
}
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SendInput(uint nInputs, Input[] pInputs, int cbSize);
[DllImport("user32.dll")]
private static extern IntPtr GetMessageExtraInfo();
public static void SendKey(ushort key)
{
Input[] inputs =
{
new Input
{
type = (int) InputType.Keyboard,
u = new InputUnion
{
ki = new KeyboardInput
{
wVk = 0,
wScan = key,
dwFlags = (uint) (KeyEventF.KeyDown | KeyEventF.Scancode),
dwExtraInfo = GetMessageExtraInfo()
}
}
}
};
SendInput((uint) inputs.Length, inputs, Marshal.SizeOf(typeof (Input)));
}
private struct Input
{
public int type;
public InputUnion u;
}
[StructLayout(LayoutKind.Explicit)]
private struct InputUnion
{
[FieldOffset(0)] public readonly MouseInput mi;
[FieldOffset(0)] public KeyboardInput ki;
[FieldOffset(0)] public readonly HardwareInput hi;
}
[StructLayout(LayoutKind.Sequential)]
private struct MouseInput
{
public readonly int dx;
public readonly int dy;
public readonly uint mouseData;
public readonly uint dwFlags;
public readonly uint time;
public readonly IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private struct KeyboardInput
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public readonly uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private struct HardwareInput
{
public readonly uint uMsg;
public readonly ushort wParamL;
public readonly ushort wParamH;
}
现在使用SendKey(0x14)
将T
密钥发送到活动窗口(或游戏)。
注意:您需要KeyEventF.Scancode
作为标记,否则wScan
属性将被忽略!