It's all in the
GetProcessesByName method of
System.Diagnostics.Process. I have included a sample below. This sample is the kind of code you may have in
Sub Main() if you are staring an application with a
Sub Main(). In the sample, "MyApplication" is the name you have given your project in Project Properties.
NB: GetProcessesByName can throw
InvalidOperationException when it cannot retrieve the process information.
Dim ThisIsTheOnlyRunningInstance As Boolean
'Try to get the list of running processes to determine if to continue in this thread
Try
ThisIsTheOnlyRunningInstance = (Diagnostics.Process.GetProcessesByName("MyApplication").Length = 1)
Catch ex As InvalidOperationException
'GetProcessByName can throw and InvalidOperationException when for any reason it cannot complete.
MessageBox.Show("Could not determine if this is the only copy running."), _
"Starting my application", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
If ThisIsTheOnlyRunningInstance Then
'Enable XP Visual Styles
Application.EnableVisualStyles()
Application.DoEvents()
'Start the app
Application.Run(New MainForm)
Else
MessageBox.Show("There is already another copy
running on this computer.", _
"Starting my application", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If