Mutex翻译过来就是 互斥体
http://dict.iciba.com/mutex/
详见MSDN关于Mutex类的详解
我们现在要实现一个程序只运行一个实例啦
首先创建一个标准的c#窗体程序,打开 Program.cs
我们可以看到自动生成的代码如下:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace MutexForm
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
我们将代码做一点修改:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
namespace MutexForm
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//只运行一个实例
bool createNew;
Mutex m = new Mutex(true, "MutexForm", out createNew);
if (createNew)
{
Application.Run(new Form1());
m.ReleaseMutex();
}
}
}
}
Ok啦,运行一下,可以看到我们的程序只会运行一个实例啦
PS:代码很简单,但是美中不足,似乎不能第二次运行的时候,激活前一个实例
如果可以激活前一个实例就好了
希望达人赐教哈。。