Reputation: 141
I'm trying to implement single instance application using mutex. the application can run only one instance from a given directory. i tried to implement it in Applicationsevents class but it's not working.
I replicated it with a test harness with a single form. my ApplicationEvents.vb code:
Private Sub SingleInstanceCheck(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
Dim strLoc As String = Assembly.GetExecutingAssembly().Location
Dim fileInfo As IO.FileSystemInfo = New IO.FileInfo(strLoc)
Dim sExeName As String = fileInfo.Name
strLoc = strLoc.Replace("\", "//")
Using mutex As New Threading.Mutex(False, "Global\" + strLoc)
If Not mutex.WaitOne(0, False) Then
File.WriteAllText("c:\log.txt", "instance already running")
Environment.Exit(1)
End If
GC.Collect()
End Using
End Sub
it runs multiple instances.
Things I am not able change: 1.project setting has "Enable Application framework" ticked 2. ApplicationEvents.vb handles UnhandleException which means i cant have a module as startup.
please helpppp!!!
Upvotes: 0
Views: 2428
Reputation: 3014
If you use:
Dim newInstance as boolean
myMutex = New Threading.Mutex(True, "Global\" + strLoc, newInstance)
You can check the 'newInstance' value, if it created a new one, then there was no previous instance, otherwise if it didn't create a new one then another instance of your app did, so you can exit...
Also you need to keep the mutex around for the life of your application: your mutex will only stay around for the scope of your using statement, then it is released. You have to store it somewhere.
Upvotes: 1