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 shownas the first form)''This works well with an MDI form or a non-MDI formPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles MyBase.Load IfUBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.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 doenot conflict with other applications ActivatePrevInstance(TEXT_PROPERTY_OF_OPENING_FORM) End IfEnd Sub----------------------------------------------Add these following declarations in the form code or in a COMMON moduleif you have one.''Declarations of Windows API functionsDeclare Function OpenIcon Lib "user32" (ByVal hwnd As Long) As LongDeclare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) AsLongSub 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 Processesrunning on local machine objProcesses = Process.GetProcesses() ''Get all processes into thecollection 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 & " isalready 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 exitthe 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.