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
Private Declare PtrSafe Function IsWindowVisible Lib "user32" (ByVal hWnd As LongPtr) As Boolean
#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
Private Declare Function IsWindowVisible Lib "user32" (ByVal hWnd As Long) As Boolean
#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
If IsWindowVisible(hWnd) Then
WindowText = String(GetWindowTextLength(hWnd) + 1, Chr$(0))
Call GetWindowText(hWnd, WindowText, Len(WindowText))
If InStr(UCase(WindowText), UCase(Text)) Then Exit Do
End If
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
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
Sleep 500
OuvrirPDF_GetHandle = GetWindowByPartialText(NomPDF)
End Function
' Exemple de test
Sub testouille()
Dim h As LongPtr
h = OuvrirPDF_GetHandle
MsgBox "Handle de la fenêtre PDF : " & h
End Sub