【转】C#程序防多开

来源:互联网 发布:电动车情报网 软件 编辑:程序博客网 时间:2024/05/24 07:19

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个实例应该怎么实现?我暂时没有想到(读取注册表或外部文件除外),知道的朋友请告知一声.

 

读者个人笔记:在应用的时候同事告诉我说可以通过在程序启动的时候给程序进程设置一个固定ID,来防止通过修改文件名来多开。但是具体方法他也不记得了。在此留个记号,以供以后研究。

原创粉丝点击