利用System.Threading命名空间下的Mutex类,可以限制应用程序,让它不能同时运行多个实例。
在WinForm程序中,可以将Mutex类嵌在Main()函数中,代码如下:
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
bool fistApplicationInstance;
string mutexName = Assembly.GetEntryAssembly().FullName;
using (Mutex mutex = new Mutex(false, mutexName, out fistApplicationInstance))
{
if (fistApplicationInstance)
{
Application.Run(new Form1());
}
else
{
MessageBox.Show("另一个程序已在进行");
}
}
}
}
控制台应用程序也类型,在Maiin()方法中做相应控制即可。

本文介绍如何利用System.Threading命名空间下的Mutex类,实现限制WinForm应用程序不能同时运行多个实例的功能。通过在Main()函数中嵌入Mutex类,并在启动前检查是否存在已打开的应用实例,有效防止了程序的重复运行。
212

被折叠的 条评论
为什么被折叠?



