Avoid two instances of the same app

  • Thread starter Thread starter Nitin Agarwal
  • Start date Start date
N

Nitin Agarwal

Hi,

I am developing an application for my school project and would like to build
in a functionality, wherein whenever the application is run, it checks
whether another copy of the same application is running. If so, it would
pop an error.

Could anyone please guide me as to how can i do this.

Any help would be appreciated.

Thanks and regards,
Nitin
 
Nitin Agarwal said:
I am developing an application for my school project and would like to build
in a functionality, wherein whenever the application is run, it checks
whether another copy of the same application is running. If so, it would
pop an error.

\\\
Public Shared Function PrevInstance() As Process
Dim c As Process = Process.GetCurrentProcess()
Dim p As Process
For Each p In Process.GetProcessesByName(c.ProcessName)
If p.Id <> c.Id Then
If p.MainModule.FileName = c.MainModule.FileName Then
Return p
End If
End If
Next p
Return Nothing
End Function
///

- or -

\\\
Imports System.Threading
..
..
..
Dim m As Mutex = _
New Mutex(False, "{11C92606-65D9-4df2-9AEA-B6A4DA91BCE2}")
If m.WaitOne(10, False) Then
Application.Run(New Form1())
m.ReleaseMutex()
Else
MessageBox.Show("Application already running!")
End If
///
 
Great! thanks so much!

Herfried K. Wagner said:
\\\
Public Shared Function PrevInstance() As Process
Dim c As Process = Process.GetCurrentProcess()
Dim p As Process
For Each p In Process.GetProcessesByName(c.ProcessName)
If p.Id <> c.Id Then
If p.MainModule.FileName = c.MainModule.FileName Then
Return p
End If
End If
Next p
Return Nothing
End Function
///

- or -

\\\
Imports System.Threading
.
.
.
Dim m As Mutex = _
New Mutex(False, "{11C92606-65D9-4df2-9AEA-B6A4DA91BCE2}")
If m.WaitOne(10, False) Then
Application.Run(New Form1())
m.ReleaseMutex()
Else
MessageBox.Show("Application already running!")
End If
///
 
two questions:

#1 - where did you get the CLSID?

#2 - how would you make it so instead of showing a dialog, it activates the
running instance?
 
K. Shier said:
two questions:

#1 - where did you get the CLSID?

That's not a class ID, its a simple unique string for the application.
You can use whatever you want instead of this string. VS.NET comes with
a utility for creating GUIDs.
#2 - how would you make it so instead of showing a dialog, it activates the
running instance?

Have a look at 'AppActivate'.
 
Back
Top