Disallow Multiple Instances of an app and focus to first instance?
I know how to only allow 1 instance (using a mutex). But I don't know how to bring focus to the original application (main form) when the user tries to open a new instance. Anyone know how?
Re: Disallow Multiple Instances of an app and focus to first instance?
It has been a long time since you asked for this. I was just browsing and thought I would pass this along. You wanted to activate by Process ID. Since Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length returns >1, if the application is already open, you must compare the current process id to the ones found to figure out which one to activate. Hope this helps anyone.
VB Code:
Dim current As Process = Process.GetCurrentProcess()
Try
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length > 1 Then
Try
For i As Integer = 0 To (Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length - 1)
If (Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)(i).Id) <> current.Id Then
AppActivate(Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)(i).Id)
End If
Next
Catch ex As Exception
' Add code as desired
End Try
Return True
Else
Return False
End If
Catch ex As Exception
Return False
End Try
Re: Disallow Multiple Instances of an app and focus to first instance?
Thanks RSJIG for the suggestion. But I'm afraid the main problem which was getting the process name or ID of a mutex owner still remains. This post is about 4 years old and back to .NET FX 1.0 time. So there might be ways in newer frameworks.