如何使一个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提供的互斥功能。