Menu Content/Inhalt
Accueil arrow Outils arrow WSHShell arrow WSH Shell : Afficher les tâches

Syndication

Abonnez-vous à ce fil RSS pour être tenu informé des nouveautés de ce site.

WSH Shell : Afficher les tâches Convertir en PDF Version imprimable Suggérer par mail
Écrit par Gilles LAURENT   
14-10-2007

WSH Shell : Afficher le titre des fenêtres des tâches en cours d'exécution

Une question d'un usager sur le forum Scripting (Fr) était de savoir comment récupérer par script le titre des fenêtres des tâches en cours d'exécution. Vous pouvez retrouver ce fil ici :

Plusieurs solutions ont été proposées :

  • KO: Tasklist /v (seules les premières instances sont affichées)
  • OK: AutoIt (via la fonction WinList)
  • OK: Python (Via l'import win32gui et l'API Win32 EnumWindows et le support du callback !)
  • KO: Composant COM AutoItX (la méthode WinList n'est malheureusement pas implémentée !)
  • KO: Composant COM WScript.Application (seules les fenêtres IE et Explorer sont retournées)
  • KO: PowerShell (seules les premières instances sont affichées et Explorer est ignoré !)

J'ai donc tenté ma chance en VBScript avec la console WSH Shell. J'ai finalement abouti à la solution proposée ci-dessous qui se compose :

  • De la classe VBScript _wshTaskView.inc
    Ce module est à déposer dans le sous-dossier Include de la console WSH Shell
  • Du composant COM externe dyncall.dll (wrapper Dynawrap)
    Ce composant a besoin d'être inscrit dans le registre via la commande regsvr32
    Toutefois si la console WSH Shell est démarrée sous l'autorité de l'administrateur local alors il suffit de déposer le composant dans le sous-dossier Com de la console WSH Shell. Dans ce cas l'enregistrement du composant est automatique ;-)

Note : Dans le cadre de ce projet, le composant COM est utilisé pour invoquer les API Win32 suivantes :

  • GetTopWindow
  • GetWindow
  • GetWindowText
  • GetWindowThreadProcessId
  • IsWindowVisible
  • lstrcat
  • RtlMoveMemory
  • MultiByteToWideChar

Microsoft (R) Windows Script Host Version 5.6                                   
Copyright (C) Microsoft Corporation 1996-2001. Tous droits réservés.            
                                                                                
 _ _ _  ___  _ _   ___  _         _  _                                          
| | | |/ __>| | | / __>| |_  ___ | || |                                         
| | | |\__ \|   | \__ \| . |/ ._>| || |                                         
|__/_/ <___/|_|_| <___/|_|_|\___.|_||_|                                         
                                                                                
Windows Script Host (WSH) Shell v1.0.0.5 starting ...                           
                                                                                
Registering components ...                                                      
  Registering dyncall.dll ...                                                   
                                                                                
Loading external modules ...                                                    
  Loading _wshAdsi.inc ...                                                      
  Loading _wshIni.inc ...                                                       
  Loading _wshTaskView.inc ...                                                  
  Loading _wshWmi.inc ...                                                       
                                                                                
Welcome ...                                                                     
It's 14/10/2007 16:39:44 and WSH Shell is up !                                  
                                                                                
Ready.                                                                          
                                                                                
WSH D:\Test> ' le composant COM externe dyncall a été enregistré de manière     
WSH D:\Test> ' automatique lors du démarrage de la console (cela nécessite que  
WSH D:\Test> ' la console soit démarrée avec les droits appropriés)             
WSH D:\Test> ' notre nouveau module est bien présent dans la liste des modules  
WSH D:\Test> ' automatiquement chargés. Il ne reste plus qu'à créer une         
WSH D:\Test> ' instance pour en bénéficier                                      
WSH D:\Test> Set oTV=New wshTaskView                                            
WSH D:\Test> ' détermination des membres (méthodes et propriétés)               
WSH D:\Test> gm(oTV)                                                            
                                                                                
Category  Name                                                                  
--------  ----                                                                  
Function  GetAllRunningTasks ()                                                 
Property  TaskCount                                                             
Property  Version                                                               
                                                                                
WSH D:\Test> ' combien de tâches sont actuellement en cours d'exécution ?       
WSH D:\Test> echo oTV.TaskCount                                                 
15                                                                              
WSH D:\Test> ' affichage formaté des tâches en cours (id, nom et titre)         
WSH D:\Test> ' comme le fait si bien le gestionnaire des tâches Windows         
WSH D:\Test> ft oTV.GetAllRunningTasks(),"Name","","*"                          
                                                                                
Id    Name            WindowTitle                                               
--    ----            -----------                                               
3916  cmd.exe         C:\WINDOWS\system32\cmd.exe                               
2068  cmd.exe         Cmd Running as Administrator                              
808   explorer.exe    D:\Test                                                   
808   explorer.exe    Poste de travail                                          
3396  IEXPLORE.EXE    glsft.free.fr - WSH Shell : Les modules externes - Micr...
3396  IEXPLORE.EXE    Google - Microsoft Internet Explorer                      
3240  IEXPLORE.EXE    Aide et Support en ligne Microsoft - Microsoft Internet...
2696  msimn.exe       microsoft.public.fr.scripting - Outlook Express           
672   notepad.exe     test.cmd - Bloc-notes                                     
1812  notepad.exe     History.log - Bloc-notes                                  
2332  notepad.exe     _wshTaskView.inc - Bloc-notes                             
3860  powershell.exe  Windows PowerShell                                        
148   taskmgr.exe     Gestionnaire des tâches de Windows                        
3496  vmware.exe      Windows 2000 Professional - VMware Workstation            
3884  WSH.exe         Windows Script Host (WSH) Shell                           
                                                                                
WSH D:\Test> ' NOTE: on remarque que trois instances d'Internet Explorer sont   
WSH D:\Test> ' affichées ici avec deux Id dictincts (3396) et (3240)            
WSH D:\Test> ' - le premier processus (3396) gère deux instances de fenêtre     
WSH D:\Test> ' - le second processus (3240) gère une seule instance de fenêtre  
WSH D:\Test> ' NOTE: les instances de l'explorateur de fichiers sont également  
WSH D:\Test> ' affichées (808)                                                  
WSH D:\Test> ' Enjoy !                                                          
WSH D:\Test>                                                                    

Listing 1 : _wshTaskView.inc

  1. '
  2. '    Windows Script Host (WSH) Shell
  3. '    (c) 2007 Gilles LAURENT
  4. '    wshTaskView Class v1.0.0.1
  5. '
  6. Option Explicit
  7. Class WSHTaskView
  8. ' =========================
  9. ' == PRIVATE PROPERTIES
  10. ' =========================
  11.     Private oFs, oRe, oDyn
  12. ' =========================
  13. ' == PUBLIC PROPERTIES
  14. ' =========================
  15.     Public Property Get TaskCount ()
  16.         TaskCount = UBound (Me.GetAllRunningTasks ())            
  17.     End Property
  18.     Public Property Get Version ()
  19.         oRe.Pattern="v(\d\.\d.*)"    
  20.         Version = oRe.Execute (oFs.OpenTextFile ("Include\_wshTaskView.inc", 1, False).ReadAll ())(0).SubMatches (0)
  21.     End Property
  22. ' =========================
  23. ' == PRIVATE MEMBERS
  24. ' =========================
  25.     Private Sub Class_Initialize ()
  26.         ' initialisation des objets
  27.         Set oDyn = CreateObject ("DynamicWrapper")
  28.         Set oFs = CreateObject ("Scripting.FileSystemObject")
  29.         Set oRe = New RegExp
  30.         ' déclaration des API Win32 (prototypes)
  31.         oDyn.Register "User32.dll", "GetTopWindow", "f=s", "r=h", "i=h"
  32.         oDyn.Register "User32.dll", "GetWindow", "f=s", "r=h", "i=hu"
  33.         oDyn.Register "User32.dll", "GetWindowText", "f=s", "r=l", "i=hll"
  34.         oDyn.Register "User32.dll", "GetWindowThreadProcessId", "f=s", "r=l", "i=hl"
  35.         oDyn.Register "User32.dll", "IsWindowVisible", "f=s", "r=t", "i=h"
  36.         oDyn.Register "kernel32.dll", "lstrcat", "f=s", "r=l", "i=ws"
  37.         oDyn.Register "kernel32.dll", "RtlMoveMemory", "f=s", "r=l", "i=lll"
  38.         oDyn.Register "kernel32.dll", "MultiByteToWideChar", "f=s", "r=l", "i=llllll"
  39.         ' définition des propriétés de l'expression régulière
  40.         oRe.IgnoreCase = True
  41.         oRe.Multiline = False
  42.         oRe.Global = True
  43.     End Sub
  44.     Private Sub Class_Terminate ()
  45.         ' libération des objets
  46.         Set oFs = Nothing
  47.         Set oRe = Nothing
  48.         Set oDyn = Nothing
  49.     End Sub
  50.     Private Function LPSTR (str)
  51.         Dim lpSrc, lpDest
  52.         lpSrc = oDyn.lstrcat (str, "")
  53.         lpDest = oDyn.lstrcat (LPSTR, "")
  54.         LPSTR = CLng (0)
  55.         oDyn.RtlMoveMemory lpDest+8, lpSrc+8, 4
  56.     End Function
  57.     Private Function ReadMemory (lpSrc, nOffset, nSize)
  58.         Dim lpDest
  59.         lpDest = oDyn.lstrcat (ReadMemory, "")
  60.         ReadMemory = CLng (0)
  61.         oDyn.RtlMoveMemory lpDest+8, lpSrc+nOffset, nSize
  62.     End Function
  63. ' =========================
  64. ' == PUBLIC MEMBERS
  65. ' =========================
  66.     Public Function GetAllRunningTasks ()
  67.         ' déclaration des variables
  68.         Dim oProc
  69.         Dim hWnd
  70.         Dim nLen
  71.         Dim strTitleBuf, strPid, strTitle
  72.         Dim arrART(): Redim arrART (0)
  73.         Dim CP_ACP: CP_ACP = 0
  74.         ' initialisation des buffers (allocation mémoire)
  75.         strTitleBuf = String (256, VBNullChar)
  76.         strPid = String (4, VBNullChar)
  77.         ' définition du header
  78.         arrART (0) = "Id" & shell.strTableFieldSep & "Name" & shell.strTableFieldSep & "WindowTitle"
  79.         ' recherche du handle de la fenêtre racine (top level)
  80.         hWnd = oDyn.GetTopWindow (0)
  81.         ' énumération des fenêtres visibles
  82.         do
  83.             If hWnd <> 0 And oDyn.IsWindowVisible (hWnd) Then
  84.                 nLen = oDyn.GetWindowText (hWnd, LPSTR (strTitleBuf), Len (strTitleBuf))
  85.                 If nLen > 0 Then
  86.                     strTitle = String (nLen + 1, VBNullChar)
  87.                     oDyn.MultiByteToWideChar CP_ACP, 0, LPSTR (strTitleBuf), -1, LPSTR (strTitle), Len (strTitle)
  88.                     strTitle = Replace (strTitle, Chr (0), "")
  89.                     If strTitle <> "Program Manager" Then
  90.                         oDyn.GetWindowThreadProcessId hWnd, LPSTR (strPid)
  91.                         Set oProc = GetObject ("winmgmts:/root/cimv2:Win32_Process.Handle='" & ReadMemory (LPSTR (strPid), 0, 4) & "'")
  92.                         Redim Preserve arrART (UBound (arrART) + 1)
  93.                         arrART (UBound (arrART)) = oProc.ProcessId & shell.strTableFieldSep & oProc.Name & shell.strTableFieldSep & strTitle
  94.                     End If
  95.                 End If
  96.             End If
  97.             hWnd = oDyn.GetWindow (hWnd, 2)
  98.         Loop Until hWnd = 0
  99.         GetAllRunningTasks = arrART
  100.     End Function
  101. End Class

Dernière mise à jour : ( 10-04-2008 )
 
< Précédent   Suivant >