Click here to Skip to main content
15,884,628 members
Articles / Programming Languages / C#
Tip/Trick

A simple way to ensure only one instance is running.

Rate me:
Please Sign up or sign in to vote.
4.50/5 (8 votes)
31 Jul 2011CPOL 24.1K   5   6
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)


Written By
CEO
Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?

Comments and Discussions

 
GeneralMy vote of 5 Pin
Joezer BH28-Jan-13 22:15
professionalJoezer BH28-Jan-13 22:15 
GeneralVB lets you select this using a tick-box in the project prop... Pin
Paul_Williams3-Aug-11 6:27
Paul_Williams3-Aug-11 6:27 
GeneralReason for my vote of 1 Interaction.AppActivate Pin
ElDim1-Aug-11 19:51
ElDim1-Aug-11 19:51 
GeneralReason for my vote of 5 Very useful! Got it working in my a... Pin
Greg Otto1-Aug-11 12:14
Greg Otto1-Aug-11 12:14 
GeneralReason for my vote of 5 Good one! Pin
DrABELL31-Jul-11 4:43
DrABELL31-Jul-11 4:43 
GeneralUsing mutex Pin
nurko1010-Aug-11 2:07
nurko1010-Aug-11 2:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.