防止程序多开的两种方法
【程序篇】防止程序多开的两种方法 <a target=_blank href="http://bbs.cskin.net/forum.php?mod=viewthread&tid=105&fromuid=2446">http://bbs.cskin.net/forum.php?mod=viewthread&tid=105&fromuid=2446</a> (出处: CSkin论坛) 互斥对象防止程序多开
private void Form1_Load(object sender, EventArgs e) { bool Exist;//定义一个bool变量,用来表示是否已经运行 //创建Mutex互斥对象 System.Threading.Mutex newMutex = new System.Threading.Mutex(true, "仅一次", out Exist); if (Exist)//如果没有运行 { newMutex.ReleaseMutex();//运行新窗体 } else { MessageBox.Show("本程序一次只能运行一个实例!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);//弹出提示信息 this.Close();//关闭当前窗体 } }
进程检查
private void Form1_Load(object sender, EventArgs e) { //获取当前活动进程的模块名称 string moduleName = Process.GetCurrentProcess().MainModule.ModuleName; //返回指定路径字符串的文件名 string processName = System.IO.Path.GetFileNameWithoutExtension(moduleName); //根据文件名创建进程资源数组 Process[] processes = Process.GetProcessesByName(processName); //如果该数组长度大于1,说明多次运行 if (processes.Length > 1) { MessageBox.Show("本程序一次只能运行一个实例!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);//弹出提示信息 this.Close();//关闭当前窗体 }