Single Instance Applications

This is in C# with .NET 2.0.

Working with processes

In the .NET framework 2.0 we use the System.Diagnostics.Process class.

To get the current process:

Process currentProcess = Process.GetCurrentProcess();

To get a list of processes by name:

Process[] processesWithSameName = Process.GetProcessesByName("MyProcessName");

Each running process has its own unique ID.

Process[] processesWithSameName = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
 
foreach (Process process in processesWithSameName)
{
  if (process.Id != currentProcess.Id)
  {
    MessageBox.Show("Another process with the same name was detected.");
  }
}

Single instance using a mutex

See this thread on Channel 9.

 
[STAThread]
static void Main()
{
  bool grantedOwnership;
  using (System.Threading.Mutex mtxSingleInstance =
    new System.Threading.Mutex(true, "A2907A9C-63D7-474e-ADA6-EA910EF1493D", out grantedOwnership))
  {
    if (grantedOwnership)
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
    }
    else
    {
      ShowWindow(FindWindow(null, "Form1"), SW_RESTORE);       
    }
  }
}
 
private const int SW_RESTORE = 9;
 
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
 
[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hwnd, int cmndShow);

This code uses a mutex. The first instance of the application will acquire a lock on the mutex. Then when the application is started subsequently it will not be able to acquire the mutex. The mutex will be released when the first application exits.

The code also uses interop to access the Win32 functions FindWindow() and ShowWindow().

 
software_development/dotnet/single_instance_applications.txt · Last modified: 2008/04/08 12:10 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki