title: GetAsyncKeyState to repeat same key
body: <pre><code>Imports InputManager
  'Using inputmanager to send keys
  
      Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
      hotkeyx = GetAsyncKeyState(Keys.X)
                  If hotkeyX &lt; 0 Then
              Keyboard.KeyUp(Keys.X)
              System.Threading.Thread.Sleep(5)
              Keyboard.KeyDown(Keys.X)
              System.Threading.Thread.Sleep(5)
      End If
      'Timer1 interval is 10 ms
  </code></pre>
  
  <ol>
  <li>The problem is if I do this, when I press and hold X for about 5 seconds then
  it will just repeat X indefinitely even if I release the X key.</li>
  <li>I only want X repeated when I hold down X key then I want it to stop when I release it.</li>
  </ol>
  
  <p>Help me please.</p>
  
  <p>If I add, Keyboard.KeyUp(Keys.X) following Keyboard.KeyDown(Keys.X) then it will not repeat it when I release the key but then the key will be repeated much slower and GetAsyncKeyState will take longer to detect the key press so I can't do that. –  user1785594 2 hours ago   </p>
  
  <p>Also If I increase Timer1 interval to 50 ms, then async repeat problem will become less frequently but it still does that and I don't think that's the right way to do it.</p>
  
  <pre><code>Dim cntNo As Int32 = 0
  
      Private Sub CheckKey(ByVal key As Integer)
              Dim state = GetAsyncKeyState(key)
              If state &lt; 0 Then
                  prevState(key) = True
                  Keyboard.KeyUp(CType(key, Keys))
  'keyup to simulate X keyUp for target program
                  System.Threading.Thread.Sleep(5)
  '5ms interval is required for me
  
                  Keyboard.KeyDown(CType(key, Keys))
                  System.Threading.Thread.Sleep(5)
  'Above code is much better than previous one but it does unintended async repeat sometimes
                  cntNo = cntNo + 1
                  If cntNo &gt; 10 Then
                      Keyboard.KeyUp(CType(key, Keys))
                      cntNo = 0
                  End If
  'If it's repeated for 10 times then send keyUP to end it
  
              ElseIf prevState(key) Then
                  prevState(key) = False
                  Keyboard.KeyUp(CType(key, Keys))
              End If
          End Sub
  
       Private Sub Timer4_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer4.Tick
                        CheckKey(Keys.X)
                 End Sub
  </code></pre>
  
  <p>'-Thanks to Hans Passant, I made a working code but I think I used improper way to do this though.
  Since program require keyUP to simulate X key press, it will have the same problem although not as often as before, I don't know how to solve it so I just added key up for every 10 rounds. Is there a better solution?</p>