Option Explicit
#If VBA7 Then
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare PtrSafe Function GetDesktopWindow Lib "user32" () As LongPtr
Private Declare PtrSafe Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hWnd As LongPtr) As Long
Private Declare PtrSafe Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As LongPtr, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare PtrSafe Function GetWindow Lib "user32" (ByVal hWnd As LongPtr, ByVal wCmd As Long) As Long
#Else
Private Declare Function GetDesktopWindow Lib "user32" () As Long
Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
#End If
Private Const GW_HWNDNEXT = 2
Private Const GW_CHILD = 5
'--------------------------------------------
'Get Window's Handle by Window's partial text
'--------------------------------------------
#If VBA7 Then
Private Function GetWindowByPartialText(Text As String) As LongPtr
Dim hWnd As LongPtr
#Else
Private Function GetWindowByPartialText(Text As String) As Long
Dim hWnd As Long
#End If
Dim WindowText As String
hWnd = GetDesktopWindow()
hWnd = GetWindow(hWnd, GW_CHILD)
Do While Not hWnd = 0
WindowText = String(GetWindowTextLength(hWnd) + 1, Chr$(0))
Call GetWindowText(hWnd, WindowText, Len(WindowText))
If InStr(UCase(WindowText), UCase(Text)) Then Exit Do
hWnd = GetWindow(hWnd, GW_HWNDNEXT)
Loop
'Return value
GetWindowByPartialText = hWnd
End Function
' Fonction qui lance le PDF et renvoie le handle
Function OuvrirPDF_GetHandle() As LongPtr
Dim CheminPDF As Variant
Dim NomPDF As String
Dim i As Integer
CheminPDF = Application.GetOpenFilename("Fichiers PDF (*.pdf), *.pdf", 1, "Ouvrir un fichier")
If VarType(CheminPDF) = vbBoolean Then Exit Function
NomPDF = Mid(CheminPDF, InStrRev(CheminPDF, "\") + 1)
NomPDF = Left(NomPDF, Len(NomPDF) - 4)
' Lance le PDF avec l'application par défaut
'Shell "explorer """ & CheminPDF & """", vbNormalFocus
With CreateObject("Shell.Application")
.Open CheminPDF
End With
' Attend jusqu'à 3 secondes le Handle de la fenêtre
For i = 1 To 10
Sleep 300
OuvrirPDF_GetHandle = GetWindowByPartialText(NomPDF)
If Not OuvrirPDF_GetHandle = 0 Then Exit For
Next i
End Function
' Exemple de test
Sub testouille()
Dim h As LongPtr
h = OuvrirPDF_GetHandle
MsgBox "Handle de la fenêtre PDF : " & h
End Sub