05 June 2011

Windows App - Detecting Running Instance

Code to detect if an windows application instance is already running or not:

static class Program
    {
        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main()
        {
            if (IsPreviousInstanceRunning)
            {
                MessageBox.Show("Another instance of this application is already running...", "Application already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmMain());
            }
        }

        private static bool IsPreviousInstanceRunning
        {
            get
            {
                // get the name of our process
                string proc = Process.GetCurrentProcess().ProcessName;
                // get the list of all processes by that name
                Process[] processes = Process.GetProcessesByName(proc);
                // if there is more than one process...
                if (processes.Length > 1)
                    return true;
                return false;
            }
        } 
    }