Click here to Skip to main content
Click here to Skip to main content

A simple way to ensure only one instance is running.

By , 31 Jul 2011
Rate this:
Please Sign up or sign in to vote.
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:
 
        // 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)

About the Author

OriginalGriff
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?
Follow on   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberEdo Tzumer28-Jan-13 22:15 
GeneralVB lets you select this using a tick-box in the project prop... PingroupPaul Pencoed3-Aug-11 6:27 
GeneralReason for my vote of 1 Interaction.AppActivate PinmemberElDim1-Aug-11 19:51 
GeneralReason for my vote of 5 Very useful! Got it working in my a... PinmemberGreg Otto1-Aug-11 12:14 
GeneralReason for my vote of 5 Good one! PinmemberDrABELL31-Jul-11 4:43 
GeneralUsing mutex Pinmembernurko1010-Aug-11 2:07 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 31 Jul 2011
Article Copyright 2011 by OriginalGriff
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid