Home
Manage Your Code
Snippet: Allowing Only One Instance of an Application (C#)
Title: Allowing Only One Instance of an Application Language: C#
Description: Allowing Only One Instance of an Application to run at one time Views: 358
Author: raheel farooq Date Added: 4/2/2008
Copy Code  
1    // Detect existing instances

2    string processName = Process.GetCurrentProcess().ProcessName;
3    Process[] instances = Process.GetProcessesByName(processName);
4
5    if (instances.Length > 1)
6    {
7        MessageBox.Show("This application is already running.");
8        return;
9    }
10    // End of detection
Usage
static void Main()
{
    // Detect existing instances
    string processName = Process.GetCurrentProcess().ProcessName;
    Process[] instances = Process.GetProcessesByName(processName);

    if (instances.Length > 1)
    {
        MessageBox.Show("This application is already running.");
        return;
    }
    // End of detection

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}
Notes
simply paste the code in the start of the main function "static void Main()"of your project like given in the "usage" portion.