#Region " Code to handle a single instance of the application "
'Windows API
Declare Function OpenIcon Lib "user32" (ByVal hwnd As Long) As Long
Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
'''
''' Function to check and see if an instance of the application is already open
''' '''
Name of the application
'''
True/False '''
Public Shared Function IsAlreadyOpen(ByVal sApp As String) As Boolean
'Check running processes to see if application is already running
Dim pProcess As Process() = System.Diagnostics.Process.GetProcessesByName(sApp)
If pProcess.Length > 1 Then 'If > 1 then its already running
Return True
Else 'Not running
Return False
End If
End Function
Public Shared Sub ActivatePrevInstance(ByVal argStrAppToFind As String)
Dim PrevHndl As Long
Dim result As Long
Dim objProcess As New Process 'Variable to hold individual Process
Dim objProcesses() As Process 'Collection of all the Processes running on local machine
objProcesses = Process.GetProcesses() ''Get all processes into the collection
For Each objProcess In objProcesses
If UCase(objProcess.ProcessName) = UCase(argStrAppToFind) Then
If Not String.IsNullOrEmpty(objProcess.MainWindowTitle) Then
'MessageBox.Show(objProcess.MainWindowTitle)
PrevHndl = objProcess.MainWindowHandle.ToInt32()
Exit For
End If
End If
Next
If PrevHndl = 0 Then Exit Sub 'if No previous instance found exit the application.
''If found
result = OpenIcon(PrevHndl) 'Restore the program.
result = SetForegroundWindow(PrevHndl) 'Activate the application.
End 'End the current instance of the application.
End Sub
#End Region