1. 程式人生 > >C# winform 判斷程式是否已經啟動,防止重複開啟

C# winform 判斷程式是否已經啟動,防止重複開啟

判斷程式是否已經執行,使程式只能執行一個例項有很多方法,下面記錄兩種,

方法1:執行緒互斥

複製程式碼

    static class Program
    {
        private static System.Threading.Mutex mutex;

        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            mutex = new System.Threading.Mutex(true, "OnlyRun");
            if (mutex.WaitOne(0, false))
            {
                Application.Run(new MainForm());
            }
            else
            {
                MessageBox.Show("程式已經在執行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
        }
    }

複製程式碼

方法2:

這種檢測程序的名的方法,並不絕對有效。因為開啟第一個例項後,將執行檔案改名後,還是可以執行第二個例項。

複製程式碼

    static class Program
    {
        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // get the name of our process
            string p = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            // get the list of all processes by that name
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(p);
            // if there is more than one process
            if (processes.Length > 1)
            {
                MessageBox.Show("程式已經在執行中", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
            else
            {
                Application.Run(new MainForm());
            }
        }
    }

複製程式碼