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: 00324
Viewed: 6289
Rating:  [Rated by 5 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:

1Const KEYEVENTF_EXTENDEDKEY = &H1
2Const KEYEVENTF_KEYUP = &H2
3Private 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:

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

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

CODE:

8PressKey vbKeyA

To press the A key.

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

CODE:

9Private Function PressString(strString)
10   strString = UCase(strString)
11   For i = 1 To Len(strString)
12      a = Mid(strString, i, 1)
13      b = Asc(a)
14      PressKey (b)
15   Next i
16End Function

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

CODE:

17PressString "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