VBS How to determine if a program is running

6.6k Views Asked by At

I need a way to determine if a process with a visible window is open, using VBScript.

For example, when I close the SolidWorks window, the SolidWorks.exe process remains running.

How can I find out which is which? Any suggestions?

1

There are 1 best solutions below

0
On

Maybe you could use the command line program tasklist.exe to find out if the right window is open.

If you run tasklist /V /FI "IMAGENAME eq sldworks.exe" and find a difference between the process you are interested in and the other one, this might work.

Assuming there is a specific window title you can look for:

Dim pid = GetProcessId("sldworks.exe", "That window title")
If pid > 0 Then
    MsgBox "Yay we found it"
End If

where GetProcessId() is this

Function GetProcessId(imageName, windowTitle)
    Dim currentUser, command, output, tasklist, tasks, i, cols

    currentUser = CreateObject("Wscript.Network").UserName

    command = "tasklist /V /FO csv"
    command = command & " /FI ""USERNAME eq " + currentUser + """"
    command = command & " /FI ""IMAGENAME eq " + imageName + """"
    command = command & " /FI ""WINDOWTITLE eq " + windowTitle + """"
    command = command & " /FI ""SESSIONNAME eq Console"""
    ' add more or different filters, see tasklist /?

    output = Trim(Shell(command))
    tasklist = Split(output, vbNewLine)

    ' starting at 1 skips first line (it contains the column headings only)
    For i = 1 To UBound(tasklist) - 1
        cols = Split(tasklist(i), """,""")
        ' a line is expected to have 9 columns (0-8)
        If UBound(cols) = 8 Then
            GetProcessId = Trim(cols(1))
            Exit For
        End If
    Next
End Function

Function Shell(cmd)
    Shell = WScript.CreateObject("WScript.Shell").Exec(cmd).StdOut.ReadAll()
End Function

You don't have to return the PID, you could also return True/False or any other information tasklist provides. For reference, the tasklist column indexes are:

  • 0: "Image Name"
  • 1: "PID",
  • 2: "Session Name"
  • 3: "Session#"
  • 4: "Mem Usage",
  • 5: "Status"
  • 6: "User Name"
  • 7: "CPU Time"
  • 8: "Window Title"

More advanced interaction with processes is available through the WMI. Plenty of examples how to use that in VBScript are all over the Internet. Search for Win32_Process.