Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A simple way to ensure only one instance is running.

4.50/5 (8 votes)
31 Jul 2011CPOL 25.5K  
Sometimes, you want to only run a single instance of an application - this makes it very simple to do. An Extension method that checks, switches and kills as necessary.
I have a simple application which stores standard replies in a database, and allows me to copy them to the clipboard on a simple click or double click. That way, I can easily answer questions which come up often with a polite, simple response such as
Don't post this under Questions & Answers - if you got the code from an article, then there is a "new message" button at the bottom of that article, which causes an email to be sent to the author. They are then alerted that you wish to speak to them.
Posting this here relies on them "dropping by" and realising it is for them.
without typing too much.

I recently realized that my Standard Replies app could run multiple instances which could get confusing if I added a new reply to one instance - it wouldn't necessarily show in the other. The simplest answer was to make it a single instance application. It's not difficult to do, but it seems sensible to code it as an extension method to the Process class:

C#
// Sets the window to be foreground
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);
// Activate or minimize a window
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;
/// <summary>
/// Ensures that just a single instance of an application is running.
/// </summary>
/// <remarks>
/// Checks if this is the only executing example of this process.
/// If it is, all well and good.
/// Otherwise, switches the focus to the other instance, and
/// terminates this process.
/// </remarks>
/// <example>
/// In program.cs:
///
/// [STAThread]
/// static void Main()
///     {
///     Process.GetCurrentProcess().SingleInstance();
///     Application.EnableVisualStyles();
///     Application.SetCompatibleTextRenderingDefault(false);
///     Application.Run(new frmMain());
///     }
/// </example>
/// <param name="thisProcess"></param>
public static void SingleInstance(this Process thisProcess)
    {
    foreach (Process proc in Process.GetProcessesByName(thisProcess.ProcessName))
        {
        if (proc.Id != thisProcess.Id)
            {
            ShowWindow(proc.MainWindowHandle, SW_RESTORE);
            SetForegroundWindow(proc.MainWindowHandle);
            thisProcess.Kill();
            }
        }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)