Bonjour a tous,
J'ai un code qui me permet de fermer une fenêtre (si elle est ouverte) d'un logiciel puis d'activer la fenêtre principale de ce même logiciel.
Le problème est que ça fonctionne mais pas a chaque fois, j'ai l'impression qu'il ne trouve pas la fenêtre a certain moment.
Voici mon code:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3 Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As Any) As Long 'API pour rechercher le handle d'une fenetre Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long 'API pour envoyer une commande a une fenetre avec son Handle Public Const WM_CLOSE = &H10et dans un autre module:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 Application.EnableEvents = True Do FenRun = FindWindow(vbNullString, "fenetre a fermer") Call PostMessage(FenRun, WM_CLOSE, 0, 0) DoEvents Loop While FenRun <> FindWindow(vbNullString, "Afficher les runs") 'Sleep 800 Application.ScreenUpdating = True On Error GoTo Execute_V10 Application.EnableEvents = False Application.ScreenUpdating = False 'AppActivate "fenetre pricipale" Call principale_Activate
Voici le code que j'ai adapté a mes besoins, mais ne connaissant pas le monde des API windows, je suis un peu perdu et je ne comprend pas pourquoi des fois ça fonction et certaines fois je suis obligé d'activer puis désactiver manuellement la fenêtre avant que le code fonctionne.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 Option Explicit Public Declare PtrSafe Function GetDesktopWindow Lib "user32" () As Long Public Declare PtrSafe Function GetWindow& Lib "user32" (ByVal hwnd&, ByVal wCmd&) Public Declare PtrSafe Function GetWindowLong& Lib "user32" _ Alias "GetWindowLongA" (ByVal hwnd&, ByVal nIndex&) Public Declare PtrSafe Function GetWindowText& Lib "user32" Alias _ "GetWindowTextA" (ByVal hwnd&, ByVal lpString$, ByVal aint&) Private Const mconMAXLEN = 255 Sub principale_Activate() Dim hwnd&, Style&, Title$, i& hwnd = GetWindow(GetDesktopWindow(), 5) Do While hwnd Title = GetCaption(hwnd) If Len(Title) Then ' Enum visible windows only If GetWindowLong(hwnd, -16) And &H10000000 Then If InStr(1, Title, "cut rite", 1) Then AppActivate Title Exit Sub End If End If End If hwnd = GetWindow(hwnd, 2) Loop MsgBox "Aucune fenêtre principale trouvée !", 64 End Sub Private Function GetCaption(hwnd&) As String Dim i%, Buffer$: Buffer = String$(254, 0) i = GetWindowText(hwnd, Buffer, 255) If i Then GetCaption = Left$(Buffer, i) End Function
Partager