C#阻止应用程序多开:使用Mutex类
程序员文章站
2024-02-29 12:43:52
...
一、问题
当我们编译调试好程序后,打开程序生成的exe文件,发现几乎可以无限次的打开(当然内存要足够多)。
如图:
二、所用类与方法
using System.Threading;
Mutex mutex = new Mutex(true, "随便起的名字", out bool createNew);
//之后判断createNew的值若为false,说明已经存在一名为"随便起的名字"的进程了。若为true,则表示可开启一个新的进程。
mutex.ReleaseMutex();//释放Mutex
三、步骤
打开项目中的主函数中添加下面的代码:
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Mutex mutex = new Mutex(true, "测试来及萨蒂i", out bool createNew);
if(createNew)
{
Application.Run(new Form1());
mutex.ReleaseMutex();
}
else
{
MessageBox.Show("只能打开一个程序!");
}
}
}
四、效果
之后,就可以看到效果了:
上一篇: iptables命令详解和使用案例
推荐阅读