Wednesday 25 November 2009

WinForms - Use Mutex to Ensure Only One Instance

The following code enforces that only one instance of your WinForms application runs at every time:

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
// this is true only if the namedMutex created newly in the context of the current application
bool namedMutexCreated = false;

using (Mutex mtex = new Mutex(true, "BeaconClientService", out namedMutexCreated))
{
if (namedMutexCreated)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

// when the form is closed, the mutext is released
mtex.ReleaseMutex();
}
else
{
MessageBox.Show("An instance of Beacon Client Service is already running.", "Service Is Running", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error occured when running the Beacon Client Service, message: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

More:

No comments: