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;

   try
   {
      proc = Process.GetProcessesByName(ProcessName);
      return proc.Length;
   }
   finally
   {
      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

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

End Function

Comments

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

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

Silent Renew and the "login_required" Error When Using oidc-client

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader