123neri123 123neri123 - 3 months ago 27x
Vb.net Question

How to simulate held down keys with VB.NET or C#?

How can I send keys to another application so that they're held down?
I want something like

keystate(keys.A) = down
(to hold button)


keystate(keys.A) = up
(to release the button)

  • i dont care if its c# or visual basic i know them

  • using visual studio


If you want to send multiple keys in a row, use SendKeys.Send


If you want to hold down keys, you need to import a User32 library call:

Private Declare Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)

You'll also need MapVirtualKey. This transfers the layout of the keys on your physical board (driver oriented) to a virtual keyset that's invariant of hardware (software oriented.)

<DllImport("User32.dll", SetLastError:=False, CallingConvention:=CallingConvention.StdCall, _
       CharSet:=CharSet.Auto)> _
Public Shared Function MapVirtualKey(ByVal uCode As UInt32, ByVal uMapType As MapVirtualKeyMapTypes) As UInt32
End Function

Then just do something like this:

Private Sub HoldKeyDown(ByVal key As Byte, ByVal durationInSeconds As Integer)
    Dim targetTime As DateTime = DateTime.Now().AddSeconds(durationInSeconds)
    keybd_event(key, MapVirtualKey(key, 0), 0, 0) ' Down
    While targetTime.Subtract(DateTime.Now()).TotalSeconds > 0
    End While
    keybd_event(key, MapVirtualKey(key, 0), 2, 0) ' Up
End Sub