The easiest option is to use a mutex.
In your windows forms application, open the program.cs file and add the following references:
using System.Threading;
using System.Reflection
Then change the Main() method as follows:
static class Program
{
[STAThread]
static void Main()
{
string mutexName = String.Format("Local\\{0}", Assembly.GetExecutingAssembly().GetName().Name);
using (Mutex mutex = new Mutex(false, mutexName))
{
if (!mutex.WaitOne(0, false))
{
MessageBox.Show("An instance of this application is already running.",
"[APPLICATION_NAME]",
MessageBoxButtons.OK,
MessageBoxIcon.STOP);
return;
}
GC.Collect();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
GC.KeepAlive(mutex);
}
}
}
The first instance of the application will still run as normal, however if a second instance is started, the messagebox will be displayed and as soon as the OK button is clicked the application will close.
This article was published on the 26th March 2008
Licence information / Terms of use
All code supplied on this site be it within the assembly or code samples is supplied as is. I take no responsibility for any of the code provided. As always with code samples & frameworks, use it at your own risk.
All applications and tutorials where C# code is provided in either text or a class file may be freely used and modified if you so desire.
The assembly is compiled against .net 3.5. There will not be a 2.0 compatible version so if you wish to use the assebly you will need to be using Visual Studio 2008 with the .net 3.5 framework installed.
The assembly may be used within in commercial and personal software free of charge but may not be resold on its own. To clarify, you may build an application on top of any of the functionality provided by the assembly (e.g using the code contract framework inside your application).
Support, suggestions and bugs can be submitted via my contact form however it is offered on a limited basis with no guaranteed response or response time.
Any updates or bug fixes will be included in any further downloads once releases on the site but note that there is no "update" service available so you would need to manually update any code.