PDA

Click to See Complete Forum and Search --> : Capturing keyboard events


Dimension
Jul 12th, 2001, 02:16 PM
I have a program that is invisible to the user that i want to keep track of all keys hit on the keyboard. The form is minimized therefore i can't use any of the objects methods because none of them will have focus. Is there an api that can do this? Any help is greatly appreciated.

Vlatko
Jul 12th, 2001, 02:49 PM
The best way is to install a system wide hook. That is not very hard. It can be a little trouble for you if you don't know C++ because the hook procedure has to be put in a standard DLL (made in C++, Delpji.ASM).

Vlatko
Jul 12th, 2001, 02:50 PM
Another way is with a timer. Not very accurate (if the user types fast)


'In a module
Public Const DT_CENTER = &H1
Public Const DT_WORDBREAK = &H10
Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Declare Function DrawTextEx Lib "user32" Alias "DrawTextExA" (ByVal hDC As Long, ByVal lpsz As String, ByVal n As Long, lpRect As RECT, ByVal un As Long, ByVal lpDrawTextParams As Any) As Long
Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long
Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Declare Function SetRect Lib "user32" (lpRect As RECT, ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Global Cnt As Long, sSave As String, sOld As String, Ret As String
Dim Tel As Long
Function GetPressedKey() As String
For Cnt = 32 To 128
'Get the keystate of a specified key
If GetAsyncKeyState(Cnt) <> 0 Then
GetPressedKey = Chr$(Cnt)
Exit For
End If
Next Cnt
End Function
Sub TimerProc(ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long)
Ret = GetPressedKey
If Ret <> sOld Then
sOld = Ret
sSave = sSave + sOld
End If
End Sub

'In a form
Private Sub Form_Load()
Me.Caption = "Key Spy"
'Create an API-timer
SetTimer Me.hwnd, 0, 1, AddressOf TimerProc
End Sub

Private Sub Form_Unload(Cancel As Integer)
'Kill our API-timer
KillTimer Me.hwnd, 0
'Show all the typed keys
MsgBox sSave
End Sub