使用互斥量禁止程序运行多次

Posted on 2019-01-26 00:47  努力成长静待花开  阅读(331)  评论(0编辑  收藏  举报

实现效果:

  

知识运用:

  Mutex类的ReleaseMutex方法  //来释放Mutex对象

  构造函数如下:public Mutex (bool  initiallyOwned, string name, bool createdNew)

  

实现代码:

        static System.Threading.Mutex mutex;        //设为静态 防止被回收 使mutex失效
        private void Form1_Load(object sender, EventArgs e)
        {
            bool exists;                 //定义变量 用来指示是否已经运行
            mutex = new System.Threading.Mutex(true,"仅一次",out exists);
            if (exists)
                mutex.ReleaseMutex();   //释放mutex对象
            else
            {
                MessageBox.Show("本程序只允许运行一次");
                this.Close();
            }
        }