Simulating VB's App.PrevInstance in VB.NET and C#

Disclaimer: The following information is for educational uses only. Please do not use to leak classified information.

Versions of Visual Basic prior to VB.NET had an App object (not to be confused with .NET's Application object) which exposed some useful functionality, including the PrevInstance function, which indicated whether or not a previous instance of the application was currently running. This function does not exist in VB.NET, but the functionality itself is present. This posting will show you how to use it, both in VB.NET and C#.

To determine if a previous version of the application is running, we can use the Process object contained within the System.Diagnostics namespace. Specifically, the Process object's GetProcessesByName() method provides the functionality we need. Take a look at the C# code below (a using System.Diagnostics; declaration is implied):

public int iGetProcessCount( string ProcessName )
   Process[] proc = null;

      proc = Process.GetProcessesByName(ProcessName);
      return proc.Length;
      proc = null;


The function above takes the name of a process as a parameter, and returns an integer representing the number of instances of that process are currently running. Note: the process name should not include .exe. For example, to determine how many instances of Notepad are running, you'd pass "Notepad" to the function, not "Notepad.exe". The GetProcessesByName method returns an array of Process objects. To simulate the PrevInstance function, we'd pass the name of our app into the above function, and check for a result greater than 1.

Here's the same function in VB.NET (an Imports System.Diagnostics declaration is implied):

Public Function iGetProcessCount(ByVal ProcessName As String)
   Dim proc() As Process = Nothing

      proc = Process.GetProcessesByName(ProcessName)
      Return proc.Length
      proc = Nothing
   End Try

End Function


Anonymous said…
You should check for instance > 0, not 1.

Popular Posts

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets

A Red Herring When Using Moq to Mock Methods With Optional Parameters