Winform中只运行运行一个实例的方法

在Program类的main方法按如下代码编写即可

 1  static void Main()
 2         {
 3             if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
 4             {
 5                 MessageBox.Show("程序已经运行了一个实例,该程序只允许有一个实例");
 6                 Application.Exit();
 7                 return;
 8             }
 9             bool createNew;
10             using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew))
11             {
12                 if (!createNew)
13                 {
14                     MessageBox.Show("应用程序已经在运行中...");
15                     System.Threading.Thread.Sleep(1000);
16                     System.Environment.Exit(1);
17                     Application.Exit();
18                 }
19             }
20 
21             Application.EnableVisualStyles();
22             Application.SetCompatibleTextRenderingDefault(false);
23             Application.Run(new MainForm());
24         }

 

posted on 2017-12-14 10:39  鲁广广  阅读(255)  评论(0)    收藏  举报

导航