Sending keys to the last used program.

To send keys to the last used application you need to set the Windows input focus to its window and allow time for it to start processing messages first. In other words, you will need a variable which is continuously updated with the Hwnd of the foreground window, a timer event to update the variable and a sub to allow time between your setting the focus and actually sending the keys.

This is how it's done::


Declared at module level:

Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Declare Function GetForegroundWindow Lib "user32" () As Long
Declare Function GetTickCount Lib "kernel32" () As Long
Global MainApp As Long


Timer Event to update MainApp:

Private Sub Get MainApp_Timer() '... about 1 second intervals
Dim Appwindow As Long
Dim xx As Long
'.........
Appwindow = GetForegroundWindow&()
For xx = 0 To Forms.Count - 1
     If Appwindow = Forms(xx).hwnd Then Exit Sub '...Our app has the focus so don't change MainApp
Next xx
MainApp = Appwindow
End Sub


Sub to delay before sending keys:

Sub Opendelay(Msec%)
Dim Start As Long
Dim Check As Long
'.........
Start = GetTickCount&()
Do
    DoEvents
    Check = GetTickCount&()
    If Check < Start Or Check > Start + Msec Then Exit Do
Loop
End Sub


To send the keys:

xx = SetForegroundWindow&(MainApp)
Opendelay 200
Sendkey "Whatever", Wt