c#启动单个程序(互斥机制)

    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            try
            {
                bool ret;
                System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out   ret);
                if (ret)
                {

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new FrmMain());
                    m.ReleaseMutex();

                }
                else
                {
                    MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行,请不要同时运行多个本程序。\n\n这个程序即将退出。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    // 提示信息,可以删除。
                    System.Diagnostics.Process[] killprocess = System.Diagnostics.Process.GetProcessesByName(Application.ProductName);
                    foreach (System.Diagnostics.Process p in killprocess)
                    {
                        // if p.Id==Application.pro
                        int id = Process.GetCurrentProcess().Id;
                        if (id != p.Id)
                        {
                            p.Kill();
                            p.WaitForExit();
                        }

                    }

                    //Application.Exit();//退出程序  
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new FrmMain());
                    m.ReleaseMutex();

                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("程序出现异常,即将关闭,请重新运行"+exp.ToString());
                System.Environment.Exit(0);
            }

        }//main
    }



posted @ 2010-06-12 11:35  kevinzhwl  阅读(267)  评论(0编辑  收藏  举报