Login | Register | Home
Enter a few key words that relate to your problem:
Title: How to simulate a key press
Description: Shows you how you can use API to simulate a key press.
Posted By: eAi
Section: Windows API Calls
Code ID: 0324
Viewed: 5549
Rating: [Rated by 0 people]  
Line Numbers: On|Off

Can't find what you wanted?
Note: Most programs will need to be active before they can recieve key presses. You can use AppActivate() for this.

Put these lines at the top of your form's source code in the declarations section:

CODE:

Const KEYEVENTF_EXTENDEDKEY = &H1
Const KEYEVENTF_KEYUP = &H2
Private Declare Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Now put this function in below it:

CODE:

Private Function PressKey(KeyCode As KeyCodeConstants)
   keybd_event KeyCode, 0, 0, 0 ' press the key
   keybd_event KeyCode, 0, KEYEVENTF_KEYUP, 0 ' release the key
End Function

Now, all you have to do is call the function! Just do it like this:

CODE:

PressKey vbKeyA

To press the A key.

Heres a bonus function you can add in, after the other function:

CODE:

Private Function PressString(strString)
   strString = UCase(strString)
   For i = 1 To Len(strString)
      a = Mid(strString, i, 1)
      b = Asc(a)
      PressKey (b)
   Next i
End Function

This will allow you to send a complete string. For example:

CODE:

PressString "Hello World"

Note: As you are simulating key strokes, If caps lock is on, all the keys will be capitals. With this code, all the keys will be capitals anyway. Not sure why, but theres a problem with small letters.
Site contents and design © Ed Lyons 2004 - 2006