C#防止窗口重复打开

修改Program.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Test
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            bool is_createdNew1;
            bool is_createdNew2;
            System.Threading.Mutex mu1 = null;
            System.Threading.Mutex mu2 = null;

            try
            {
                #region 檢查程式是否重複執行

                // 第一關:在同目錄執行相同程式的情況下不允許重複執行
                string mutexName1 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Replace(System.IO.Path.DirectorySeparatorChar, '_');
                mu1 = new System.Threading.Mutex(true, "Global\" + mutexName1, out is_createdNew1);
                if (!is_createdNew1)
                {
                    return;
                }

                // 第二關:在完全相同的傳入參數下不允許重複執行,避免數據重複計算
                string mutexName2 = "Args_" + String.Join("_", args).Replace(System.IO.Path.DirectorySeparatorChar, '_');
                mu2 = new System.Threading.Mutex(true, "Global\" + mutexName2, out is_createdNew2);
                if (!is_createdNew2)
                {
                    return;
                }

                #endregion

                //DoSomething();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainWindow());  //MainWindow是窗口名
        }
    }
}
原文地址:https://www.cnblogs.com/blogpro/p/11462984.html