我编写了程序以将输入发送到游戏和桌面应用程序,而不是从键盘获取输入。结果如下:
Windows 7(32 位):在游戏和桌面应用程序中完美运行。
Windows 8(64 位):不能在游戏中工作,但在 notepad.exe 中工作。
那么为什么它不适用于win 8?
这是代码:
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[StructLayout(LayoutKind.Explicit)]
struct MouseKeybdHardwareInputUnion
{
[FieldOffset(0)]
public MOUSEINPUT mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
public uint type;
public MouseKeybdHardwareInputUnion mkhi;
}
enum SendInputFlags
{
KEYEVENTF_EXTENDEDKEY = 0x0001,
KEYEVENTF_KEYUP = 0x0002,
KEYEVENTF_UNICODE = 0x0004,
KEYEVENTF_SCANCODE = 0x0008,
}
[DllImport("user32.dll")]
static extern UInt32 SendInput(UInt32 nInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] INPUT[] pInputs, Int32 cbSize);
public static void StrokeKey(ushort codeOfKey)
{
INPUT[] InputData = new INPUT[1];
ushort ScanCode = codeOfKey;
InputData[0].type = 1;
InputData[0].mkhi.ki.wScan = (ushort)ScanCode;
InputData[0].mkhi.ki.dwFlags = (uint)SendInputFlags.KEYEVENTF_SCANCODE;
if (SendInput(1, InputData, Marshal.SizeOf(InputData[0])) == 0)
{
String blad = "SendInput failed with code: " + Marshal.GetLastWin32Error().ToString();
System.Diagnostics.Debug.WriteLine(blad);
}
}
public static void ReleaseKey(ushort codeOfKey)
{
INPUT[] InputData = new INPUT[1];
ushort ScanCode = codeOfKey;
InputData[0].type = 1;
InputData[0].mkhi.ki.wScan = (ushort)ScanCode;
InputData[0].mkhi.ki.dwFlags = (uint)SendInputFlags.KEYEVENTF_KEYUP | (uint)SendInputFlags.KEYEVENTF_SCANCODE;
InputData[0].mkhi.ki.time = 0;
InputData[0].mkhi.ki.dwExtraInfo = IntPtr.Zero;
SendInput(1, InputData, Marshal.SizeOf(InputData[0]));
}