PDA

View Full Version : How to determine if program is already open.



craigers77
11-24-2008, 09:05 AM
I have a routine that calls an external program using the shell command. That part is no problem.

But, is there a way to determine if the program is already open? If yes then make it the active window and come to the foreground. If no then open it.

Thanks.

Kenneth Hobs
11-24-2008, 02:40 PM
Paste this into a new Module.

Option Explicit

Private Declare Function BringWindowToTop Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long

'Some other class names: http://support.microsoft.com/kb/72918
Const gcClassnameMSWord = "OpusApp"
Const gcClassnameMSExcel = "XLMAIN"
Const gcClassnameMSIExplorer = "IEFrame"
Const gcClassnameMSVBasic = "wndclass_desked_gsk"
Const gcClassnameNotePad = "Notepad"
Const gcClassnameMyVBApp = "ThunderForm"

Sub IsNotepadRunning()
Dim s As String, rc As Variant, tf As Boolean

s = "Notepad.exe"
tf = ISexeRunning(s)
If tf Then
BringWindowToTop FindWindow(gcClassnameNotePad, vbNullString)
Else
If vbYes = MsgBox(s & " is not running? Do you wish to start it?" & tf, vbQuestion + vbYesNo, "Start NotePad") Then
rc = Shell("Notepad", vbNormalFocus)
End If
End If
Exit Sub
End Sub

Function ISexeRunning(EXEName As String) As Boolean
Dim tf As Boolean
Dim oShell As Object, oWMI As Object, cApps As Object
Dim sQuery As String

Set oShell = CreateObject("Shell.Application")
Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
sQuery = "Select Name From Win32_Process Where Name='" & Left(EXEName, 15) & "'"
Set cApps = oWMI.ExecQuery(sQuery)
tf = cApps.Count > 0
Set cApps = Nothing
Set oWMI = Nothing
Set oShell = Nothing
ISexeRunning = tf
End Function

craigers77
11-25-2008, 08:00 AM
Thanks for that, but it gets hungup on this section of code. I get a compile error, says it can't find the project or library.

The "Left(EXEName, 15)" seems to throw it off.

sQuery = "Select Name From Win32_Process Where Name='" & Left(EXEName, 15) & "'"

Kenneth Hobs
11-25-2008, 08:56 AM
Left would not cause a reference error. You can use just EXEName if you like. The Left was for something else I was doing.

If you are using Vista, then it won't work I suspect. This site shows which ones it does work with. http://www.it-visions.de/Scripting/WMIReferenz.asp?C_Klasse=Win32_Process

I wrote a VB.NET program that checks for a running EXE. If that interests you, I could point you to that EXE program. Otherwise, an all API solution would be needed. Since I don't have Vista, I can't test to see if that method would work for Vista.

You may not have Windows Scripting Host installed or it may be disabled by administrators. If you can install it, check out http://vbnet.mvps.org/index.html?code/wmi/wmi_processmonitor.htm