Sometimes you have to prevent user from starting more than one instance of your application. First you have to check if your application is already running.
VB.NET code snippet below returns true if a second instance of the application has been started.
''' <summary> ''' Check if an instance of this application is running ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function IsProcessRunning() As Boolean ' Try If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).GetUpperBound(0) > 0 Then Return True Else Return False End If Catch Return False End Try End Function
If the function returns true, you may show a message box to tell the user that application is already running.
The function above can be made more general by giving process name as a parameter. Below is a modified version that returns number of running process instances.
''' <summary> ''' Return number of process instances ''' </summary> ''' <param name="ProcessName">Processes friendly name</param> ''' <returns>Number of instances</returns> ''' <remarks></remarks> Public Function ProcessesRunning(ByVal ProcessName As String) As Integer ' Try Return Process.GetProcessesByName(ProcessName).GetUpperBound(0) + 1 Catch Return 0 End Try End Function
Now you can check, for example, how many instances of the Notepad are running:
MessageBox.Show("There are " & ProcessesRunning("Notepad").ToString & _ " Notepad instances running", _ "Process Count", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information)
You can use also this version to test if your application is running:
If ProcessesRunning(Process.GetCurrentProcess.ProcessName) > 1 Then ' Second instance was started End If
And then notify user that the application is already running.