Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Declare PtrSafe Function GetWindow Lib "user32" _
(ByVal hwnd As LongPtr, ByVal wCmd As Long) As LongPtr
Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As LongPtr, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As LongPtr
Public Function getLastHandle(Optional sec As Long = 0) As LongPtr
'patricktoulon
Static dicoHandle As Object ' le dico en static
'si sec= 0 on reinitialise le dico
If sec = 0 Then
Set dicoHandle = CreateObject("scripting.dictionary")
End If
Dim hwnd As LongPtr
tim = Timer
'on recommence le bourrin tant que le timer n'est pas atteint
Do While Timer - tim < (sec + 1)
hwnd = FindWindow(vbNullString, vbNullString) 'on commence avec la première fille du desktop
DoEvents
Do While hwnd <> 0 'on boucle tant que hwnd <> de 0
DoEvents
'Debug.Print hwnd
'si il y a un timer c'est qu'on cherche un handle on est donc dans un second lancement de la fonction
'alors si on en trouve un différent des existant alors c'est lui la dernière fen$etre ouverte
'donc on le recupère dans le return et on sort de la fonction
If Not dicoHandle.exists(hwnd) And sec > 0 Then
getLastHandle = hwnd 'le return de la fonction renvoie le handle
Set dicoHandle = Nothing 'on peut bruler le dico
Exit Function 'on peut sortir
Else
'si sec= 0 on est dans le premier lancement qui ne sertt qu'a stocker les handle dans le dico
dicoHandle(hwnd) = ""
End If
hwnd = GetWindow(hwnd, 2) 'on passe a la suivante
Loop
Loop
End Function
Sub test()
Dim h As LongPtr
'ici on utilise pas l'appel pour un return on lance comme une sub ca va remplir le dico des fen^tre existantes
getLastHandle
'on teste en lancant un fichier
ShellExecute 0, "open", "C:\Users\patricktoulon\Desktop\cBenchmark.txt", "", "", 1 ' SW_SHOWNORMAL
'cette fois ci on va utiliser le return de la fonction qui doit me renvoyer le handle (la dernière fenêtre ouverte)
h = getLastHandle(2)
'on affiche pour le test
MsgBox h
End Sub