禁止WinForm程序开启多次

static Mutex vMyMutex;

 

static void Main

{

 

bool vF;
            vMyMutex = new Mutex(true, "Transactions", out vF);   // xxxxxx 是自己取的名稱
            if (!vF)
            {                                                                   // 表示已經有同名的 Mutex
                vMyMutex.Close();
                vMyMutex = null;
                MessageBox.Show("该程式已开启,不可以开启多个相同的程式.", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Application.ApplicationExit += OnApplicationExit;

 

}

 

 

static void OnApplicationExit(object sender, EventArgs e)
        {
            if (vMyMutex != null)
            {

                try
                {
                    vMyMutex.ReleaseMutex();// 釋放 Mutex
                    vMyMutex.Close();
                }
                catch (Exception ex)
                {
                    MyLog vMyLog = new MyLog();
                    vMyLog.WriteLog(ex.Message);
                }
            }
        }

        public static void ApplicationExit()
        {
            for (int i = 0; i < vFormArrayList.Count; i++)
            {
                ((Form)vFormArrayList[i]).Close();
            }
            Application.DoEvents();
            Application.ExitThread();
        }

 

posted @ 2010-03-19 10:50  马建康  阅读(290)  评论(0编辑  收藏  举报