I am trying to prevent my program from running multiple instances at any given time. I have read about using mutex and windows events, however both threads were several years old, and I'm curious if with .net4 there is a more simple, and more elegant way to deal with this? I thought I had read about a setting for the form that allowed you to deny multiple instances by the property? Could someone shed some light on what the safest and/or simplest way to prevent multiple instances of a program is?
The safest way is to use the built-in support in .NET, WindowsFormsApplicationBase.IsSingleInstance property. Hard to guess if it is appropriate, you didn't make much effort describing your exact needs. And no, nothing changed in the past 5 years. – Hans Passant Jan 7 at 0:38
This was the best answer but Hans didn't submit it as an answer.
In VB you can set this at the project level (Properties > General) for Winforms projects.
In C# you can use code similar to this.. needs conversion of course..
Dim tGrantedMutexOwnership As Boolean = False
Dim tSingleInstanceMutex As Mutex = New Mutex(True, "MUTEX NAME HERE", tGrantedMutexOwnership)
If Not tGrantedMutexOwnership Then
'
' Application is already running, so shut down this instance
'
Else
'
' No other instances are running
'
End If
Whoops, I forgot to mention that you will need to place GC.KeepAlive(tSingleInstanceMutex)
after your Application.Run() call
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With