Search code examples
vbapdfsendkeys

VBA SendKeys to another window not working


I have the following macro which is intended to quickly switch two PDFs. After 8 quick switches macro should go to the next pages of both PDFs and repeat the procedure. Unfortunately, macro scrolls first declared PDF only. Any ideas how to amend it?

Private Declare PtrSafe Function BringWindowToTop Lib "user32" (ByVal lngHWnd As LongPtr) As LongPtr

Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr

Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMiliseconds As Long)


Sub switching_pdfs()

Dim i As Integer, j As Integer

ptr1 = FindWindow(vbNullString, "Some PDF 1.pdf - Acrobat Reader")
ptr2 = FindWindow(vbNullString, "Some PDF 2.pdf - Acrobat Reader")

For i = 1 To 30
    For j = 1 To 4
       BringWindowToTop (ptr1)
       Sleep 100
       BringWindowToTop (ptr2)
       Sleep 100
    Next j
BringWindowToTop (ptr1)
Application.SendKeys "{RIGHT}": Sleep 500: DoEvents 'should move to the next page in the first PDF
BringWindowToTop (ptr2)
Application.SendKeys "{RIGHT}": Sleep 500: DoEvents 'should move to the next page in the second PDF
Next i
End Sub

I also tried to use SendMessage, but it does not want to move any PDF to the next page.


Solution

  • Try This approach. Tested and Working. You may change the Wait numbers to make the delay longer. Make sure the PDF files are named properly and there are no extra Spaces on the file name.

    Sub switching_pdfs()
        Dim i As Integer, j As Integer
        Dim ptr1 As String, ptr2 As String
        ptr1 = "Some PDF 1.pdf - Acrobat Reader"
        ptr2 = "Some PDF 2.pdf - Acrobat Reader"
    
        For i = 1 To 30
            For j = 1 To 4
               AppActivate ptr1
               Wait 0.5
               AppActivate ptr2
               Wait 0.5
            Next j
            AppActivate ptr1
            Send "{RIGHT}"
            Wait 1
            AppActivate ptr2
            Send "{RIGHT}"
            Wait 1
        Next i
    End Sub
    Function Send(pData As String)
        SendKeys pData, True
        Wait 0.5
    End Function
    Function Wait(Optional pWaitTime As Single = 0.1)
        Dim StartTime
        StartTime = Timer
        Do While (Timer < StartTime + pWaitTime)
            DoEvents
        Loop
    End Function