winform程序限制只能打开一个进程
有很多方案,先来最傻瓜式的 :
1 static class Program 2 { 3 /// <summary> 4 /// 应用程序的主入口点。 5 /// </summary> 6 [STAThread] 7 static void Main() 8 { 9 if (System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length > 1) 10 { 11 MessageBox.Show("已经有一个运行了"); 12 } 13 else 14 { 15 16 Application.Run(new Form1()); 17 } 18 19 } 20 }
再来一种
1 static class Program 2 { 3 [STAThread()] 4 public static void Main() 5 { 6 bool ret; 7 System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out ret); 8 if (ret) 9 { 10 //System.Windows.Forms.Application.EnableVisualStyles(); //这两行实现 XP 可视风格 11 //System.Windows.Forms.Application.DoEvents(); 12 System.Windows.Forms.Application.Run(new Form1()); 13 // frmMain 为你程序的主窗体,如果是控制台程序不用这句 14 m.ReleaseMutex(); 15 } 16 else 17 { 18 MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行,请不要同时运行多个本程序。\n\n这个程序即将退出。 ", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); 19 // 提示信息,可以删除。 20 Application.Exit();//退出程序 21 } 22 } 23 }