保证应用程序只有一个实例运行

        public static System.Diagnostics.Process RunningInstance()
        {
            System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess();
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(current.ProcessName);
            //查找相同名称的进程
            foreach (System.Diagnostics.Process process in processes)
            {
                //忽略当前进程
                if (process.Id != current.Id)
                {
                    //确认相同进程的程序运行位置是否一样.
                    if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        //Return the other process instance.
                        return process;
                    }
                }
            }
            //No other instance was found, return null.
            return null;
        }

在main中调用

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            System.Diagnostics.Process instance = RunningInstance();
            if (instance == null)
            {
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已有程序打开");
            }

 示例二

        public static bool ExistOtherOne()
        {
            Process process = Process.GetCurrentProcess();
            Process[] processes = System.Diagnostics.Process.GetProcessesByName(process.ProcessName);
            if (processes.Length > 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

 

posted @ 2018-07-18 11:33  恋上微笑的天使  阅读(294)  评论(0编辑  收藏  举报