how do I ensure only one instance of an application can execute concurrently

  • Thread starter Thread starter Chris Anderson
  • Start date Start date
C

Chris Anderson

Could someone please tell me how I ensure only one instance of an
application can execute concurrently?
 
using System.Runtime.InteropServices;

#region Check to see if it's already runnin
// Get this process name
string proc = Process.GetCurrentProcess().ProcessName

// Get all the processes with the same name
Process[] procs = Process.GetProcessesByName(proc)

// If there is more than 1 including this one then return
if(procs.Length > 1

// Assume there is our process, which we will terminate,
// and the other process, which we want to bring to the
// foreground. This assumes there are only two processes
// in the processes array, and we need to find out which
// one is NOT us
// Get our process
Process p = Process.GetCurrentProcess()
int n = 0; // Assume the other process is at index 0
// If this process id is OUR process ID..
if(procs[0].Id == p.Id

// then the other process is at index 1
n = 1

// Get the window handle
IntPtr hWnd = procs[n].MainWindowHandle
// If iconic, we need to restore the window
if(IsIconic(hWnd)

ShowWindowAsync(hWnd, SW_RESTORE)


// Bring it to the foreground
SetForegroundWindow(hWnd)
// Exit this process
return

#endregion
 
Chris Anderson said:
Could someone please tell me how I ensure only one instance of an
application can execute concurrently?

The best way is to use a global mutex. If you search for
mutex application one instance
on groups.google.com in relevant groups, you'll get a lot of hits.

Using the process name is more dodgy, IMO, because there may be other
processes with the same name.
 
Try this, from MSDN (not tested but looks fine)

' Visual Basic .NET
Function PrevInstance() As Boolean
If
Ubound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrent
Process.ProcessName)) > 0 Then
Return True
Else
Return False
End If
End Function
 
Back
Top