C#程序防多开<只能运行一个实例>

C#程序防多开<只能运行一个实例>
方法一:
            bool createdNew; //返回是否赋予了使用线程的互斥体初始所属权
            System.Threading.Mutex instance = new System.Threading.Mutex(true, "MutexName", out createdNew); //同步基元变量
            if (createdNew) //赋予了线程初始所属权,也就是首次使用互斥体
            {
                Application.Run(new Form1()); //这句是系统自动写的
                instance.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("已经启动了一个程序,请先退出!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }

方法二:
            System.Diagnostics.Process[] pros = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            if (pros.Length > 1)
            {
                System.Windows.Forms.Application.Exit();
                return;
            }

        private bool AppAlreadyRunning()
        {
            System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess();
            System.Diagnostics.Process[] allProcess = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process process in allProcess)
            {
                if (process.Id != curProcess.Id)
                {
                    if (process.ProcessName == curProcess.ProcessName)
                        return true;
                }
            }
            return false;
        }
  通过进程名来判断,个人觉得并不可取,因为一般修改文件名进程名即改变<我尚未找到使程序进程名不变的方法,有知道请为我帖出代码,供我学习学习..>.

  如果只能运行N个实例应该怎么实现?我暂时没有想到(读取注册表或外部文件除外),知道的朋友请告知一声.
posted @ 2009-06-10 19:13  随便取个名字算了  阅读(509)  评论(0编辑  收藏  举报