Hi Matt,
Have my application class.
You can call it from Sub Main, Sub MainForm_Load or sometime later.
Regards,
Fergus
<code>
Imports System.Diagnostics.Process
Public Class clsApp
'===================================================================
Public Shared Function tThereIsAnInstanceOfThisProgramAlreadyRunning _
(Optional tToActivateThePrevInstance As Boolean = False, _
Optional ProgramTitle As String = "?") As Boolean
Dim sProcessName As String
Dim aoProcList() As System.Diagnostics.Process
sProcessName = GetCurrentProcess.ProcessName
aoProcList = GetProcessesByName (sProcessName) 'At least 1.
If aoProcList.Length = 1 Then
'There's just me.
Return False
End If
If tToActivateThePrevInstance Then
ActivateMyBetterHalf (ProgramTitle)
End If
'Another me beat me to it.
Return True
End Function
'===================================================================
Public Shared Sub ActivateMyBetterHalf _
(Optional ProgramTitle As String = "?", _
Optional tToCallAppExit As Boolean = False)
Dim MainForm As Form = Nothing
If ProgramTitle = "?" Then
MainForm = Form.ActiveForm 'Assumes that it's the main Form.
If MainForm Is Nothing Then
Throw New Exception ("No ProgramTitle and no Main Form??")
End If
ProgramTitle = MainForm.Text
MainForm.Text = "About to die" 'So AppActivate avoids self.
End If
MsgBox ("This is " & ProgramTitle & "(2) saying ""Bye, bye"" :-(")
AppActivate (ProgramTitle)
If MainForm Is Nothing = False Then
MainForm.Close
End If
If tToCallAppExit Then
Application.Exit
End If
'Or leave it to the caller to close down further as necessary.
End Sub
End Class
'===================================================================
Public Module MainMod
Public Sub Main
MsgBox ("Point 1")
If clsApp.tThereIsAnInstanceOfThisProgramAlreadyRunning (True,
"Form1") Then
Return
End If
MsgBox ("Point 2")
If clsApp.tThereIsAnInstanceOfThisProgramAlreadyRunning Then
clsApp.ActivateMyBetterHalf ("Form1")
Return
End If
Dim F As New Form1
F.Show
Application.Run()
End Sub
End Module
'===================================================================
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
MsgBox ("Point 3")
If clsApp.tThereIsAnInstanceOfThisProgramAlreadyRunning Then
'Form.ActiveForm is not yet valid. So give the name.
clsApp.ActivateMyBetterHalf (Me.Text)
Me.Close
Return
End If
End Sub
'===================================================================
Private Sub btnTest_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnTest.Click
MsgBox ("Point 4")
If clsApp.tThereIsAnInstanceOfThisProgramAlreadyRunning Then
clsApp.ActivateMyBetterHalf (,True)
End If
End Sub
</code>