February 28, 2021
Hot Topics:

More Windows Secrets for Visual Basic

  • By Karl Moore
  • Send Email »
  • More Articles »

The .NET Way of Checking for Previous Instances

There are times when it's useful to check whether another instance of your application is running. For example, when starting up your program, you may want to check whether another version is already running in the background and, if it is, give that instance the focus.

In Visual Basic 6, you had the App.PrevInstance property to do this. In VB.NET, we need to check whether the current process is running more than once. That's what our code does here, encapsulated in the PrevInstance function. It returns a True if your application is already running on the same machine:

Public Function PrevInstance() As Boolean
  If Diagnostics.Process.GetProcessesByName _
     (Diagnostics.Process.GetCurrentProcess.ProcessName) _
               .Length > 1 Then
     Return True
     Return False
  End If
End Function

You might use this code as so:

If PrevInstance() = True Then
  ' Get all previous instances
  Dim Processes() As Process
  Processes = _
    Diagnostics.Process.GetProcessesByName( _
  ' Activate the first instance
  ' Exit the current instance
End If
Top Tip: There's a little bug you may run into when using this code that turns the hair of most developers a funny shade of gray. If your application name is greater than fifteen characters, and running on either Windows NT or 2000, your code won't be able to tell whether a previous instance is running. Weird, but true. Solution: upgrade to XP or higher, or change your application name (Project > Properties).

Page 2 of 5

This article was originally published on January 29, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date