Declare Function EnumWindows Lib "user32" ( _
ByVal lpEnumFunc As Long, ByVal lParam As Long) As Boolean
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" ( _
ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" ( _
ByVal hwnd As Long) As Long
Declare Function ShowWindow Lib "user32" ( _
ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Declare Function SetForegroundWindow Lib "user32" ( _
ByVal hwnd As Long) As Long
'/// Si on tient absolument à utiliser AppActivate, il faut chercher le PID.
'/// Restriction : si la fenêtre est minimisée, elle ne sera pas activée.
Declare Function GetWindowThreadProcessId Lib "user32" ( _
ByVal hwnd As Long, lpdwProcessId As Long) As Long
'///
Const SW_SHOWNORMAL = 1
Dim SearchString$
Dim myHwnd&
Dim A$
Dim B$ '°°° Pour visualiser (à virer par la suite)
Public Function EnumWindowsProc(ByVal hwnd As Long, ByVal lParam As Long) As Boolean
Dim LenChaine&
Dim bool As Boolean
'--- Enumération du nom de chaque fenêtre ---
bool = True
LenChaine& = GetWindowTextLength(hwnd)
A$ = Space(LenChaine&)
GetWindowText hwnd, A$, LenChaine& + 1
'--- Si le nom contient la chaîne recherchée ---
If InStr(1, A$, SearchString) > 0 Then
B$ = A$ '°°° Pour visualiser (à virer par la suite)
myHwnd& = hwnd 'on récupère son Handle
bool = False
End If
'--- Tant que bool=True on continue l'énumération ---
EnumWindowsProc = bool
End Function
Sub ActiveFenetre()
Dim ProcessID&
'---
'--- Chaîne à rechercher dans le titre de la fenêtre ---
SearchString$ = "Paint" 'à adapter (ex : "MonAppli Bidule")
'---
EnumWindows AddressOf EnumWindowsProc, ByVal 0&
'°°° Pour visualiser (à virer par la suite) °°°
If B$ <> "" Then
MsgBox "On a trouvé ''" & B$ & "''"
B$ = ""
Else
MsgBox "Aucune fenêtre contenant ''" & SearchString$ & "'' n'a été trouvée."
End If
'°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
'--- Active la fenêtre (c'est la bonne approche)---
ShowWindow myHwnd&, SW_SHOWNORMAL 'agrandit la fenêtre si elle est minimisée
SetForegroundWindow myHwnd& 'place la fenêtre au 1er plan
''/// Si on tient absolument à utiliser AppActivate, il faut chercher le PID.
''/// Restriction : si la fenêtre est minimisée, elle ne sera pas activée.
''--- Recherche du PID ---
'GetWindowThreadProcessId myHwnd&, ProcessID
'If ProcessID& > 0 Then AppActivate ProcessID&
''///
End Sub