如何使用directInput发送发布密钥?

时间:2012-10-15 16:09:04

标签: c# keyboard directinput

我想使用直接输入发送密钥。我能够发送按键。但是我不知道如何发送密钥释放以避免按键被按下。

这是我的代码:

struct INPUT
{
  public UInt32 type;
  public ushort wVk;
  public ushort wScan;
  public UInt32 dwFlags;
  public UInt32 time;
  public UIntPtr dwExtraInfo;
  public UInt32 uMsg;
  public ushort wParamL;
  public ushort wParamH;

}

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 StrokeW()
{
  INPUT[] InputData = new INPUT[1];
  ushort ScanCode = 0x11;
  InputData[0].type = 1;
  InputData[0].wScan = (ushort)ScanCode;
  InputData[0].dwFlags = (uint)SendInputFlags.KEYEVENTF_SCANCODE;
  SendInput(1, InputData, Marshal.SizeOf(InputData[0]));
}

注意:我试过这个Simulating Keyboard with SendInput API in DirectInput applications并且我无法使其正常工作

1 个答案:

答案 0 :(得分:2)

您演示的代码似乎没有遵循您发布的链接上的建议,这实际上显示了您未执行的 keyup

INPUT[] InputData = new INPUT[2];

InputData[0].type = 1; //INPUT_KEYBOARD
InputData[0].wScan = (ushort)ScanCode;
InputData[0].dwFlags = (uint)SendInputFlags.KEYEVENTF_SCANCODE;

InputData[1].type = 1; //INPUT_KEYBOARD
InputData[1].wScan = (ushort)ScanCode;
InputData[1].dwFlags = (uint)(SendInputFlags.KEYEVENTF_KEYUP 
                              | SendInputFlags.KEYEVENTF_UNICODE);

SendInput(2, InputData, Marshal.SizeOf(InputData[0]));

我从那里开始。最好显示您编写的代码,这些代码在其他帖子中使用该方法无法正常工作。