not to be opened new one while running?

mech3

Member
Joined
Sep 14, 2005
Messages
12
Programming Experience
Beginner
how to make not to be opened another copy of application while it is already running?
 
there are couple ways to prevent multiply instances of the same application. I prefer this one:

Create module file and add this code inside:
VB.NET:
Module PreventSecondInstance
'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 & " е веќе активна.", "", 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
End Module

then add this code inside load event:

VB.NET:
If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
ActivatePrevInstance("name of the form") 
End If

HTH
Regards ;)
 
i simply use:
VB.NET:
If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
  Me.Close()
End If
in the form's load event
or a variation of that in sub main, just letting it reach End Sub
 
Back
Top