Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Intermediate
Jul 27, 2002

Prevent a second process instance from running

VB6 developers can use the App.PrevInstance property to check whether there is another instance of the same process already running on the current machine. This property isn't available any longer in VB.NET, so you must retrieve this information by using the properties of the Process object.

The easiest way to do so is by means of the Process.GetProcessesByName shared method, which takes a process name and returns an array of all the processes with that name. The process name of an EXE application is usually equal to the name of the main EXE file but without the extension. So if your application is MyApp.Exe, its process name is "MyApp" and you can check whether there is already another instance of this process running with this code:


' This code requires that you have the following Imports
'   Imports System.Diagnostics

Dim procs() As Process = Process.GetProcessesByName("MyApp")
If procs.Length > 1 Then
    ' Another instance of this process is running
End If
The problem in writing a generic function that checks whether the current application is already running comes from the fact that the ProcessName property of the Process object seems to be limited to 15 characters, so longer process names are truncated. For example, create the default ConsoleApplication1 application and run this code:

' display the name of the current process
Console.WriteLine(Process.GetCurrentProcess.ProcessName)  ' => ConsoleApplicat
A safer way to retrieve a process name is to get the filename of its main module and dropping the extension. The following reusable routine uses this approach:

Function AppIsAlreadyRunning() As Boolean
    ' get the filename of the main module
    Dim moduleName As String = Process.GetCurrentProcess.MainModule.ModuleName
    ' discard the extension to get the process name
    Dim procName As String = System.IO.Path.GetFileNameWithoutExtension _
        (moduleName)
    ' return true if there are 2 or more processes with that name
    If Process.GetProcessesByName(procName).Length > 1 Then
        Return True
    End If
End Function
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap