您的位置:首页 > 其它

.net中如何只允许运行一个程序实例

2012-01-20 13:44 351 查看
如何使一个Windows应用程序只运行一个实例,看如下代码:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;

namespace MyMonitor
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Process[] ps = Process.GetProcessesByName(Process
.GetCurrentProcess().ProcessName);
if (ps.Length <= 1)
{
Application.EnableVisualStyles();
Application
.SetCompatibleTextRenderingDefault(false);
Application.Run(new EMonitor());
}
else
{
MessageBox.Show("不能打开多于一个程序实例!");
}
}
}
}
原理上来说,没有什么难的,只是不知道而已。

后来,又查到了一个方法,看下面的代码:using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace MyMonitor
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
bool bCreatedNew;
//"EMonitor" 是我的程序的主窗体的名称,但是这个名称是可以随便
//叫的,只是给互斥体取个名字而已
Mutex m = new Mutex(false, "EMonitor", out bCreatedNew);
if (bCreatedNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new EMonitor());
}
else
{
MessageBox.Show("不能打开多于一个程序实例!");
}
}
}
}

可以看到,第二段代码采用Mutex提供的互斥功能。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .net class windows