A1VBCode Forums

Application instances


http://www.a1vbcode.com/vbforums/Topic18986.aspx

By toni - 6/2/2006

Hello,

May I can get some help here... I'm trying to properly detect if more than one application instances are started.

There is App.PrevInstance, but this ensures only a previously started instance, I also need a subsequently started instance.

There is also the API function FindWindow, but this detects even the calling instance itself. I need here only if there is another instance started.

Any other suggestions?

Thanks.

By magnus - 6/22/2006

Hi,



Hope this helps.. from http://www.kbalertz.com/841291/write.application.supports.Switching.feature.using.Visual.Basic.Windows.aspx



Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load

'

Dim blnChk As Boolean

'

'Checking for the existence of an

'application that is already running.

'

If UBound(Diagnostics.Process.GetProcessesByName _

(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then

'

'Checking if there is already

'an instance that is running in this user's session.

'

blnChk = ActivatePrevInstance("FastSwitchingForm")

'

If (blnChk = False) Then

MsgBox("Another instance of " & _

Diagnostics.Process.GetCurrentProcess.ProcessName & _

" is already running in another user's session on this computer." & _

" You cannot run two instances at a time. You must use the other instance.")

End

End If

'

End If

'

End Sub



'

'This is a function to verify whether the application is already running.

'If the application is already running, set the focus on the application.

'

Private Function ActivatePrevInstance(ByVal argStrAppToFind As String) As Boolean

'

Dim PrevHndl As IntPtr = Nothing

Dim result As Boolean

Dim objProcess As New Process() 'This is a variable to hold an individual process.

Dim objProcesses() As Process 'This is a collection of all the processes that are running on the local computer.

'

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

'

For Each objProcess In objProcesses

'

'Check and then exit if there is an application that is already running.

'

If UCase(objProcess.MainWindowTitle) = UCase(argStrAppToFind) Then

MsgBox("Another instance of " & argStrAppToFind & _

" is already running on this computer. " & _

"You cannot run two instances at a time." & _

" You must use the other instance.")

PrevHndl = objProcess.MainWindowHandle

Exit For

End If

Next

'

If PrevHndl.Equals(IntPtr.Zero) Then

ActivatePrevInstance = False

Exit Function 'If no previous instance is found, exit the application.

Else

ActivatePrevInstance = True

End If

'

result = OpenIcon(PrevHndl) 'Restore the program.

result = SetForegroundWindow(PrevHndl) 'Activate the application.

End 'End the current instance of the application.

'

End Function

'