Thursday, January 29, 2009

.Net Application Single Instance

If you want to ensure that your application only runs one instance at a time, the best method is to use a Mutex.

Mutex: Short for mutual exclusion object. In computer programming, a mutex is a program object that allows multiple program threads to share the same resource, such as file access, but not simultaneously. When a program is started, a mutex is created with a unique name. After this stage, any thread that needs the resource must lock the mutex from other threads while it is using the resource. The mutex is set to unlock when the data is no longer needed or the routine is finished.

On your program.cs unit, do the following:

  
static class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
bool createdMutex = false;
Process currentProcess = Process.GetCurrentProcess();

Mutex mutex = new System.Threading.Mutex(true,
currentProcess.ProcessName + currentProcess.MachineName + " Mutex", out createdMutex);

if (createdMutex)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());

GC.KeepAlive(mutex);
}
else
{
// Application to topmost window
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (process.Id != currentProcess.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}

0 comments: