我尝试运行的程序有时会模拟GTA中的点击次数:SA。问题是它在运行时没有做任何事情。到目前为止,我已尝试过此代码:
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);
答案 0 :(得分:1)
你的第一个问题是大多数游戏都使用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);