VBA SetForegroundWindow

2.8k Views Asked by At

I'm trying to write code that periodically puts/makes sure a program is in front of all the others. To test this I have used Notepad. This code only seems to work if I open a new program in front of Notepad - and not if I open a program; then start to execute my code; then put the other already open program in front of notepad. In this case notepad only blinks orange in the taskbar. Can anybody help me with this?

Sub test()
    Dim vPID As Variant
    vPID = Shell("notepad.exe", vbMaximizedFocus)
    AppActivate vPID

    'Notepad opens, I put another program in front of it
    Application.Wait (Now + TimeValue("00:00:05"))

    'I want Notepad back in front again:
    Dim HWND As Long
    Dim SetFocus As Long
    HWND = FindWindow("Notepad", vbNullString)
    SetFocus = SetForegroundWindow(HWND)

    Application.Wait (Now + TimeValue("00:00:05"))

    'Close Notepad
    Call Shell("TaskKill /F /PID " & CStr(vPID), vbHide)
End Sub
0

There are 0 best solutions below