[ACCEPTED]-make single instance application" what does this do?-winforms
does it make it so that it's impossible 1 to open two instances at the same time?
Why not just use a Mutex? This is what 4 MS suggests and I have used it for many-a-years 3 with no issues.
Public Class Form1 Private objMutex As System.Threading.Mutex Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Check to prevent running twice objMutex = New System.Threading.Mutex(False, "MyApplicationName") If objMutex.WaitOne(0, False) = False Then objMutex.Close() objMutex = Nothing MessageBox.Show("Another instance is already running!") End End If 'If you get to this point it's frist instance End Sub End Class
When the form, in this case, closes, the 2 mutex is released and you can open another. This 1 works even if you app crashes.
Yes, it makes it impossible to open two instances at the same 9 time.
However it's very important to be aware of the bugs. With 8 some firewalls, it's impossible to open even one instance 7 - your application crashes at startup! See 6 this excellent article by Bill McCarthy for more details, and 5 a technique for restricting your application 4 to one instance. His technique for communicating 3 the command-line argument from a second 2 instance back to the first instance uses 1 pipes in .NET 3.5.
I found a great article for this topic: Single Instance Application in VB.NET.
Example 1 usage:
Module ModMain Private m_Handler As New SingleInstanceHandler() ' You should download codes for SingleInstaceHandler() class from: ' http://www.codeproject.com/Articles/3865/Single-Instance-Application-in-VB-NET Private m_MainForm As Form Public Sub Main(ByVal args() As String) AddHandler m_Handler.StartUpEvent, AddressOf StartUp ' Add the StartUp callback m_Handler.Run(args) End Sub Public Sub StartUp(ByVal sender As Object, ByVal event_args As StartUpEventArgs) If event_args.NewInstance Then ' This is the first instance, create the main form and addd the child forms m_MainForm = New Form() Application.Run(m_MainForm) Else ' This is coming from another instance ' Your codes and actions for next instances... End If End Sub End Module
Dim _process() As Process _process = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName) If _process.Length > 1 Then MsgBox("El programa ya está ejecutandose.", vbInformation) End End If
Yes you're correct in that it will only 2 allow one instance of your application to 1 be open at a time.
More Related questions