SoFunction
Updated on 2025-03-07

C# Examples that prohibit the application from launching multiple times


static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool createdNew;
//The system can recognize names with mutual exclusions, so it can be used to prohibit the application from starting twice
//The second parameter can be set to the product name:

//Every time you start the application, it will verify whether the mutex with the name SingletonWinAppMutex exists
            Mutex mutex = new Mutex(false, "SingletonWinAppMutex", out createdNew);
           
//If it is running, it will be displayed on the front end
//createdNew == false, indicating that the program has been run
            if (!createdNew)
            {
                Process instance = GetExistProcess();
                if (instance != null)
                {
                    SetForegroud(instance);
                    ();
                    return;
                }
            }
            ();
            (false);
            (new MainForm());
        }

        /// <summary>
/// Check whether the program is running
        /// </summary>
        /// <returns></returns>
        private static Process GetExistProcess()
        {
            Process currentProcess = ();
            foreach (Process process in ())
            {
                if (( != ) &&
                    (().Location == ))
                {
                    return process;
                }
            }
            return null;
        }

        /// <summary>
/// Make the program front-end display
        /// </summary>
        /// <param name="instance"></param>
        private static void SetForegroud(Process instance)
        {
            IntPtr mainFormHandle = ;
            if (mainFormHandle != )
            {
                ShowWindowAsync(mainFormHandle, 1);
                SetForegroundWindow(mainFormHandle);
            }
        }

        [DllImport("")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
    }