C#应用程序实现单例模式

该文档引自网址http://wenwen.soso.com/z/q85588071.htm

限制启动一个应用程序窗口,再启动,将把第一个启动的窗口从任务栏里还原出来。

代码如下:

 1 using Microsoft.VisualBasic.ApplicationServices;
 2 
 3     static class Program
 4     {
 5         /// <summary>
 6         /// 应用程序的主入口点。
 7         /// </summary>
 8         [STAThread]
 9         static void Main()
10         {
11             Application.EnableVisualStyles();
12             Application.SetCompatibleTextRenderingDefault(false);
13             SingleInstanceManager manager = new SingleInstanceManager();//单实例管理器
14             manager.Run(new string[]{});    
15             //Application.Run(new frmMain()); //屏蔽掉了以前的加载头
16         }
17 
18         // Using VB bits to detect single instances and process accordingly:
19         // * OnStartup is fired when the first instance loads
20         // * OnStartupNextInstance is fired when the application is re-run again
21         //    NOTE: it is redirected to this instance thanks to IsSingleInstance
22         public class SingleInstanceManager : WindowsFormsApplicationBase
23         {
24             frmMain app;
25 
26             public SingleInstanceManager()
27             {
28                 this.IsSingleInstance = true;
29             }
30 
31             protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
32             {
33                 // First time app is launched
34                 //app = new SingleInstanceApplication();
35                 //app.Run();
36                 app = new frmMain();//改为自己的程序运行窗体
37                 Application.Run(app);
38 
39                 return false;
40             }
41 
42             protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
43             {
44                 // Subsequent launches
45                 
46                 base.OnStartupNextInstance(eventArgs);
47                 app.Activate();
48                 }
49         }
50     }