C# 防止同一个应用程序运行多个实例

这里以C# Winform为例子说明,

最近在实现网络应用的时候,每个程序只能打开一次,因为会使用同一个端口,

所以为了防止客户不知道的情况下点击多次或者其他,防止这样的情况出现,写了一个小功能实现阻止这件事情发生,

说明:

"Chatter"  //程序运行的时候,在资源管理器里看到的 “ 映像名称 ”
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Windows.Forms;
 4 using System.Threading;
 5 
 6 namespace Chatter
 7 {
 8     static class Program
 9     {
10         /// <summary>
11         /// The main entry point for the application.
12         /// </summary>
13         [STAThread]
14         static void Main()
15         {
16             bool startNew;
17             Mutex m = new Mutex(false, "Chatter", out startNew);
18             if (startNew)
19             {
20                 Application.EnableVisualStyles();
21                 Application.SetCompatibleTextRenderingDefault(false);
22                 Application.Run(new Chat());
23             }
24             else
25             {
26                 MessageBox.Show("Chatter 已经运行中");
27             }
28         }
29     }
30 }