Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prevent Multiple Instances of a .NET Windows Application

How-to

Prevent Multiple Instances of a .NET Windows Application

by  PankajBanga  Posted    (Edited  )

Copy the following code in Module declaration of your application.

'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

'Variable to hold individual Process.
Dim objProcess As New Process()

'Collection of all the Processes running on local machine
Dim objProcesses() As Process

'Get all processes into the collection
objProcesses = Process.GetProcesses()

For Each objProcess In objProcesses
'Check and exit if we have SMS running already
If UCase(objProcess.MainWindowTitle) = UCase(argStrAppToFind) Then
MessageBox.Show(argStrAppToFind & " is already running.", "System", MessageBoxButtons.OK, MessageBoxIcon.Information)
PrevHndl = objProcess.MainWindowHandle.ToInt32()
Exit For
End If
Next

'If no previous instance found exit the application.
If PrevHndl = 0 Then Exit Sub

'If previous instance found.
result = OpenIcon(PrevHndl) 'Restore the program.
result = SetForegroundWindow(PrevHndl) 'Activate the application.

'End the current instance of the application.
End

End Sub


Then, use the following code in Form Load Event of your Main (starting) Form.

'Prevent multiple instances of the application.
If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
ActivatePrevInstance("YourMainFormName")
End If
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top