Multiple Instances of form in VB .Net

G

Guest

I want to open a form if it is not already open, otherwise I want to set
focus to the existing instance. I have tried three solutions from Google to
check activate the existing instance but none seem to work (At least I cannot
get them to work...probably me). Can anybody help please?
Terry

1: http://www.developerfusion.co.uk/show/3107/
2: http://devhood.com/tutorials/tutorial_details.aspx?tutorial_id=726 (This
seemed the most likely but ....???)
The other I discounted early.

The code from 2: is as follows

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

If
UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
'Send opening form's TEXT property as a parameter to the function
"ActivatePrevInstance"
ActivatePrevInstance(TEXT_OF_OPENING_FORM)
End If
End Sub

--------------------------------------------------------------------------

--Add these following declarations in the form code or in a COMMON module if
you have one.

''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
MsgBox("Another instance of " & argStrAppToFind & " is already 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 exit the
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top