Instance of program already running?

Kurt

Regular
Joined
Feb 14, 2003
Messages
99
Location
Copenhagen
How to find out whether there's already running an instance of your application when a user wants to start it?
I would like to allow only one instance running on a machine.
 
Straight from the help:

In Visual Basic 6.0, the PrevInstance property of the App object was used to determine if a previous instance of an application was running. There is no equivalent for this property in Visual Basic .NET; however, the following code can be used to test for a previous instance:

Visual Basic:
' Visual Basic .NET
Function PrevInstance() As Boolean
   If Ubound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
      Return True
   Else
      Return False
   End If
End Function
 
thanx divil. Any suggestions where the best placement would be to call this check (in the constructor of the start up form or something?), so I can cancel the start up of a second instance?
 
Make yourself a Sub Main to start the application, then only do your Application.Run(new form1()) if the check succeeds.
 
Check out [msdn]System.Threading.Mutex[/msdn]. Which will allow you to do something like this, which prevents any renaming workarounds.
Visual Basic:
       Dim objLock As New System.Threading.Mutex(False, "MyAppLock")
        Dim blnIsRunning As Boolean = Not mtxLock.WaitOne(0, False)
 
Back
Top