KnowDotNet Visual Organizer

VB6 Functionality Missing from VB.NET (PrevInstance)

by Les Smith
Print this Article Discuss in Forums

How do I prevent a user from starting multiple copies of my application?  In VB6, there was a PrevInstance method that could be tested to see if your application was already running, but that was removed from VB.NET.  

You can still test for a previous instance of the application by using the following user defined function.  If the
PrevInstance returns True, an instance of your application is already running.  To make best use of this functionality, start your application from the Main method of a module, rather than from a form.  That way you can exit the second instance of the application without ever loading a form.  In that case, you might use the following code to begin your application.

An added tip: if you need to know the user name of the logged on user, call the Environ function as shown below.  You can also use the Environ function to get the computer name.

   Public Sub Main()
      
If PrevInstance() Then Exit Sub

      
' continue with your application
      
UserName = Environ("UserName")
       ComputerName = Environ("COMPUTERNAME")

    
End Sub

  
Function PrevInstance() As Boolean
      If UBound(Diagnostics.Process.GetProcessesByName _
         (Diagnostics.Process.GetCurrentProcess.ProcessName)) _
         > 0
Then
         Return True
      Else
         Return False
      End If
   End Function

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing