zoukankan      html  css  js  c++  java
  • 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个实例应该怎么实现?我暂时没有想到(读取注册表或外部文件除外),知道的朋友请告知一声.
  • 相关阅读:
    SQL 多条件查询
    android实现程序开机自启动
    SendMessage模拟按键所需的虚拟键码
    使用API进行文件读写——CreateFile,ReadFile,WriteFile等
    VB断点拷贝大文件(WIN7系统需要更改某个API函数,具体我也忘了)
    mysql
    webstorm
    ubuntu ftp服务器
    centos ftp 服务器
    nignx
  • 原文地址:https://www.cnblogs.com/linmilove/p/1500781.html
Copyright © 2011-2022 走看看