title: How to simulate holding down a keyboard button in C++
body: <p>I am trying to make a program that would simulate holding down a keyboard button.</p>
  
  <p>This program is supposed to work in games, where holding down buttons such as <strong>W,A,S,D</strong> is required. I tested the program both in Grand Theft Auto V and Garry's Mod, but it didn't work in either of them.</p>
  
  <p>I tried using <code>SendInput</code> and <code>keybd_event</code> functions for emulating the input with no luck.</p>
  
  <pre><code>#include &lt;windows.h&gt;
  #define VK_W 0x57
  
  using namespace std;
  
  int main(){
      while(1){
          keybd_event(VK_W, 0, 0, 0);
          Sleep(3000);  //should hold W for 3 seconds
          keybd_event(VK_W, 0, KEYEVENTF_KEYUP, 0);
          Sleep(1000);
      }
      return 0;
  }
  </code></pre>
  
  <p>I've created macros using Razer's keyboard software, which work perfectly, so there must be a way to simulate the key hold input.</p>
  
  <p>I also tried creating an <code>AutoHotkey</code> script, which does work in Garry's Mod, but not in Grand Theft Auto V:</p>
  
  <pre><code>w::
  SendInput {w down}
  Sleep 3000
  SendInput {w up}
  </code></pre>
  
  <p>This script holds W for 3 seconds when <strong>W</strong> is pressed.</p>
  
  <p>I tried searching the web, but didn't find any working implementation.</p>
  
  <p><strong>EDIT: I searched around some more and found this: <a href="https://stackoverflow.com/a/3647975/1587051">https://stackoverflow.com/a/3647975/1587051</a></strong></p>
  
  <p><strong>It turns out I was using Unicode instead of keyboard scan codes combined with <code>KEYEVENTF_SCANCODE</code> flag. DirectInput games are now receiving the keystrokes correctly.</strong></p>