Detect if a particular .exe is running

Declare all coding in one module

'Constants
Public Const TH32CS_SNAPHEAPLIST = &H1
Public Const TH32CS_SNAPPROCESS = &H2
Public Const TH32CS_SNAPTHREAD = &H4
Public Const TH32CS_SNAPMODULE = &H8
Public Const TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST Or TH32CS_SNAPPROCESS Or TH32CS_SNAPTHREAD Or TH32CS_SNAPMODULE)
Public Const TH32CS_INHERIT = &H80000000
Public Const MAX_PATH As Integer = 260
'Type
Public Type PROCESSENTRY32
   dwSize As Long
   cntUsage As Long
   th32ProcessID As Long
   th32DefaultHeapID As Long
   th32ModuleID As Long
   cntThreads As Long
   th32ParentProcessID As Long
   pcPriClassBase As Long
   dwFlags As Long
   szExeFile As String * MAX_PATH
End Type
'API Declaration
Public Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
Public Declare Function Process32First Lib "kernel32" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Public Declare Function Process32Next Lib "kernel32" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Put all code below into Form

Private Sub Form_Load()
Dim hSnapShot As Long, uProcess As PROCESSENTRY32
   Dim r As Long
   lstProcess.Clear

   'Takes a snapshot of the processes and the heaps, modules, and threads used by the processes

   hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0&)

   'set the length of our ProcessEntry-type

   uProcess.dwSize = Len(uProcess)

   'Retrieve information about the first process encountered in our system snapshot
   r = Process32First(hSnapShot, uProcess)
     
   Do While r
       lstProcess.AddItem left$(uProcess.szExeFile, IIf(InStr(1, uProcess.szExeFile, Chr$(0)) > 0, InStr(1, uProcess.szExeFile, Chr$(0)) - 1, 0))
       'Retrieve information about the next process recorded in our system snapshot
       r = Process32Next(hSnapShot, uProcess)
           
   Loop
   'close our snapshot handle
   CloseHandle hSnapShot
   
   'MsgBox lstProcess.ListCount
   'search .exe in lstProcess (Listbox)
   Dim hj As Integer
   hj = 1
   For hj = 1 To lstProcess.ListCount
       If (lstProcess.List(hj) = "EXCEL.EXE") Then
           MsgBox "Microsoft Excel was running"
           
           Exit Sub
       End If
   Next hj
   
   
End Sub

In addition, you need one ListBox named as lstProcess

Enjoy it,

Hope this help you...

You might also like...

Comments

Yew Chin Sing

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Owning a computer without programming is like having a kitchen and using only the microwave oven” - Charles Petzold