Click to See Complete Forum and Search --> : Emulate a pressed key


trackgod22
May 23rd, 2001, 02:02 PM
How do I make a funcion key, F1 or so on, be pressed programmatically in Visual Basic? Also, how do execute a dos program in Visual Basic?

Iouri
May 23rd, 2001, 02:30 PM
'if you need to execute some code on F1 press, put the same code into some 'procedure and then call this proc when you want to execute it.

'Here how you capture F1 and Return on Key down event

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

public sub KeyDown()

keybd_event vk_return,0,0,0 'return key down
keybd_event vk_return,0,keyeventf_keyup,0 'return key up

end sub

here it is with F1
public sub KeyDown()

keybd_event vk_F1,0,0,0 'F1 key down
keybd_event vk_F1,0,keyeventf_keyup,0 'F1 key up

end sub

'how do execute a dos program in Visual Basic?

dim RetVal

RetVal = Shell("c:\yourprog.exe")





Iouri Boutchkine
iouri@hotsheet.com

Raptors Fan
May 23rd, 2001, 04:39 PM
The code presented gives the following compilation error:
"Constants, fixed-length strings, arrays, user-defined types and Declare statements not allowed as Public members of object modules"

Typo? By the way, is there a way to accomplish the same thing without calling API?

Cimperiali
May 24th, 2001, 03:08 AM
Now, add a .bas module to your project to use Iouri code, and put constants and declarations there
Or declare all pribìvate and put them at top of form where you want to use the code
Another way to play with keys is:
'one command button on one form
'set the form keypreview property to true or it will not work properly!
Option Explicit

Private Sub Command1_Click()
If Me.WindowState <> vbMinimized Then
Me.SetFocus
SendKeys "{F2}", True 'send a keystroke to this form
End If
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyF1 Then
Call Form_KeyDown(vbKeyF2, 0)
End If
If KeyCode = vbKeyF2 Then
'do your stuff
If Me.WindowState <> vbMinimized Then
Me.SetFocus
SendKeys "{F3}", True 'send a keystroke to this form
End If
End If
End Sub

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
Print KeyCode
End Sub


Special thanks to Lothar "the Great" Haensler, Tom Archer, Chris Eastwood, Bruno Paris and all the other wonderful people who made and make Codeguru a great place. Come back soon, you Gurus.