Aquí explico una manera de limitar manualmente la aplicación a única instancia (Single-Instance), mediante el MUTEX.


Código (vbnet) [Seleccionar]
' Single-Instance Application Example
' By Elektro
' Instructions:
' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
' 2. Copy and paste this code to replace the 'MyApplication' class contents.
' 3. Define a proper identifier for 'MutexID' property.
Namespace My
Partial Friend Class MyApplication
#Region " Properties "
''' <summary>
''' Gets the current process mutex identifier.
''' </summary>
''' <value>the current process mutex identifier.</value>
''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
Private ReadOnly Property MutexID As String
Get
' Define a Golabl Unique Identifier to name the Mutex.
Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"
If Guid.TryParse(input:=Id, result:=New Guid) Then
Return Id
Else
Throw New FormatException("The specified value is not in a valid GUID format.")
End If
End Get
End Property
#End Region
#Region " Private Methods "
''' <summary>
''' Determines whether this is the unique instance that is running for this process.
''' </summary>
''' <returns><c>true</c> if this is the unique instance; otherwise, <c>false</c>.</returns>
Private Function IsUniqueInstance() As Boolean
Dim mtx As Threading.Mutex = Nothing
Try
mtx = Threading.Mutex.OpenExisting(name:=Me.MutexID)
mtx.Close()
mtx = Nothing
Catch
mtx = New Threading.Mutex(initiallyOwned:=True, name:=Me.MutexID)
End Try
Return mtx IsNot Nothing
End Function
#End Region
#Region " Event-Handlers "
''' <summary>
''' This occurs when the application starts, before the startup Form is created.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
Handles Me.Startup
' If there is more than one instance running of this process with the same mutex then...
If Not Me.IsUniqueInstance Then ' Prevent multi-instancing.
MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
' Cancel the application execution.
e.Cancel = True
End If
End Sub
#End Region
End Class ' MyApplication
End Namespace