devxlogo

Prevent a second process instance from running

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.DiagnosticsDim procs() As Process = Process.GetProcessesByName("MyApp")If procs.Length > 1 Then    ' Another instance of this process is runningEnd 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 processConsole.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 IfEnd Function

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist