This tip describes how to avoid loading a second instance of an application when the user already has one instance running. It also sets the focus to the first instance of the .NET Windows application when you attempt to start a second instance of the same application.
This code is applicable to the .NET 1.0 and 1.1 Framework applications (Visual Studio.NET 2002 uses .NET 1.0 framework and Visual Studio.NET 2003 uses .NET 1.1 Framework).
''Add this code in the form_load event.. (the form which loaded and shown
as the first form)
''This works well with an MDI form or a non-MDI form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
If
UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurre
ntProcess.ProcessName)) > 0 Then
''Send opening form's TEXT property as a parameter to the function
"ActivatePrevInstance"
''This works well with an MDI form or a non-MDI form
''It is advised that you give a Unique name to your Form so that it doe
not conflict with other applications
ActivatePrevInstance(TEXT_PROPERTY_OF_OPENING_FORM)
End If
End Sub
--------------------------------------------
--Add these following declarations in the form code or in a COMMON module
if you have one.
''Declarations of Windows API functions
Declare Function OpenIcon Lib "user32" (ByVal hwnd As Long) As Long
Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As
Long
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
''Check and exit if we have SMS running already
If UCase(objProcess.MainWindowTitle) = UCase(argStrAppToFind)
Then
MsgBox("Another instance of " & argStrAppToFind & " is
already running on this machine. You cannot run TWO instances at a time.
Please use the other instance.")
PrevHndl = objProcess.MainWindowHandle.ToInt32()
Exit For
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
As a result of this code, the first instance of the program is given focus and the second instance is closed. If the first instance of the application was minimized, it will be restored to a normal window automatically.
Though this code is written in VB.NET, it can easily be converted into C# or JScript easily on similar grounds.