title: C# p/Invoke How to simulate a keyPRESS event using SendInput for DirectX games
body: <p>I've often struggled with simulating keyboard press events for various bots, or other GUI automating programs.</p>
  
  <p>I've managed to simulate keydown events using:</p>
  
  <pre><code>INPUT[] kInput = new INPUT[1];
  kInput[j].type = SendInputEventType.InputKeyboard;
  kInput[j].mkhi.ki.wVk = 0;
  kInput[j].mkhi.ki.wScan = (ushort) MapVirtualKey((uint) Keys.D5, 0);
  kInput[j].mkhi.ki.dwFlags = KeyboardEventFlags.SCANCODE;
  kInput[j].mkhi.ki.time = 0;
  kInput[j].mkhi.ki.dwExtraInfo = IntPtr.Zero;
  SendInput(1, kInput, Marshal.SizeOf(typeof(INPUT)));
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>INPUT[] kInput = new INPUT[1];
  kInput[1].type = SendInputEventType.InputKeyboard;
  kInput[1].mkhi.ki.wVk = '5';
  kInput[1].mkhi.ki.wScan = 0;
  kInput[1].mkhi.ki.dwFlags = 0;
  kInput[1].mkhi.ki.time = 0;
  kInput[1].mkhi.ki.dwExtraInfo = IntPtr.Zero;
  SendInput(1, kInput, Marshal.SizeOf(typeof(INPUT)));
  </code></pre>
  
  <p>and keyup events using:</p>
  
  <pre><code>kInput[1].type = SendInputEventType.InputKeyboard;
  kInput[1].mkhi.ki.wVk = 0;
  kInput[1].mkhi.ki.wScan = (ushort)MapVirtualKey((uint)Keys.D5, 0);
  kInput[1].mkhi.ki.dwFlags = KeyboardEventFlags.KEYUP;
  kInput[1].mkhi.ki.time = 0;
  kInput[1].mkhi.ki.dwExtraInfo = IntPtr.Zero;
  SendInput(1, kInput, Marshal.SizeOf(typeof(INPUT)));
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>kInput[1].type = SendInputEventType.InputKeyboard;
  kInput[1].mkhi.ki.wVk = '5';
  kInput[1].mkhi.ki.wScan = 0;
  kInput[1].mkhi.ki.dwFlags = KeyboardEventFlags.KEYUP;
  kInput[1].mkhi.ki.time = 0;
  kInput[1].mkhi.ki.dwExtraInfo = IntPtr.Zero;
  SendInput(1, kInput, Marshal.SizeOf(typeof(INPUT)));
  </code></pre>
  
  <p>And while my attempts to combine the two as:</p>
  
  <pre><code>//key down
  INPUT kInput = new INPUT[2];
  kInput[0].type = SendInputEventType.InputKeyboard;
  kInput[0].mkhi.ki.wVk = 0;
  kInput[0].mkhi.ki.wScan = (ushort) MapVirtualKey((uint) Keys.D5, 0);
  kInput[0].mkhi.ki.dwFlags = KeyboardEventFlags.SCANCODE;
  kInput[0].mkhi.ki.time = 0;
  kInput[0].mkhi.ki.dwExtraInfo = IntPtr.Zero;
  
  //Key Up
  kInput[1].type = SendInputEventType.InputKeyboard;
  kInput[1].mkhi.ki.wVk = 0;
  kInput[1].mkhi.ki.wScan = (ushort)MapVirtualKey((uint)Keys.D5, 0);
  kInput[1].mkhi.ki.dwFlags = KeyboardEventFlags.KEYUP;
  kInput[1].mkhi.ki.time = 0;
  kInput[1].mkhi.ki.dwExtraInfo = IntPtr.Zero;
  
  //sendinput
  SendInput(1, kInput, Marshal.SizeOf(typeof(INPUT)));
  </code></pre>
  
  <p>Have had varying degrees of success, I was never actually capable of emulating a key hold/press event where a DirectX (or other 3d) game would see my input in quite the way a human with a physical keyboard would...</p>
  
  <p>How would one, using SendInput, emulate a key press/hold event as seen by a DirectX game?</p>