More Windows Secrets for Visual Basic, Page 2
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 Else 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( _ Diagnostics.Process.GetCurrentProcess.ProcessName) ' Activate the first instance AppActivate(Processes(0).Id) ' Exit the current instance Application.Exit() 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).