C#创建单实例应用程序

直接上代码:

 

using System; using System.Collections.Generic; using System.Windows.Forms; using Microsoft.VisualBasic.ApplicationServices; using System.Collections.ObjectModel; namespace ADODemo { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //第一种单实例运行方式:使用线程互斥体 //bool isOnlyOne; //System.Threading.Mutex mtx = new System.Threading.Mutex(false, "OnlyOne", out isOnlyOne); //if (isOnlyOne) //{ // Application.Run(new Form2()); //} //else //{ // MessageBox.Show("当前已经运行本应用程序了,无须再次运行"); //} //第二种单实例运行方式:使用Process类来检测是否已经存在本应用程序的进程(不推荐使用) //bool isOnlyOne=true; //foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) //{ // if (p.ProcessName == "ADODemo") // { // isOnlyOne = false; // } //} //if (isOnlyOne) //{ // Application.Run(new Form2()); //} //else //{ // MessageBox.Show("当前已经运行本应用程序了,无须再次运行"); //} /*3:第三种单实例运行方式:继承WindowsFormsApplicationBase实现单实例管理器 *在 VS2008 的 MSDN 中,搜索 "单实例",找到了MS官方的实现方法。 *页面地址:单实例检测示例 ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/wpf_samples/HTML/c283e8e9-6fb5-494f-9600-826148e77046.htm *源程序下载。ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/wpf_samples/sampleexecutables/AppModel/SingleInstanceDetectionSample.zip * 需要添加对Microsoft.VisualBasic的库引用 * */ SingleInstanceManager manager = new SingleInstanceManager();//单实例管理器 manager.Run(new string[] { }); } } /// <summary> /// Using VB bits to detect single instances and process accordingly: /// * OnStartup is fired when the first instance loads /// * OnStartupNextInstance is fired when the application is re-run again /// NOTE: it is redirected to this instance thanks to IsSingleInstance /// </summary> public class SingleInstanceManager : WindowsFormsApplicationBase { Form2 app; public SingleInstanceManager() { //单实例设置,触发NEXTINSTENCE事件 this.IsSingleInstance = true; //由于没有用主窗体,设置多窗口SDI应用程序,只有当所有窗体关闭后才关闭程序 this.ShutdownStyle = ShutdownMode.AfterAllFormsClose; } protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs) { //在程序第一次运行时调用 app = new Form2(); Application.Run(app); //运行后返回FLASE return false; } protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) { base.OnStartupNextInstance(eventArgs); app.Activate(); //提示已经运行 MessageBox.Show(Application.ProductName + " 已经在运行了,不能重复运行。", "确定", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }

 

 

第二种方式我试过,不建议使用,不信你就试试吧,只要你的VS运行中,进程就存在。。,

至于第一种,如果想实现可以自动弹出已经运行的窗体的效果,见如下链接:

1:ttp://blog.csdn.net/songkexin/archive/2010/09/12/5879200.aspx

2:http://blog.csdn.net/senophen/archive/2010/04/29/5543297.aspx

你可能感兴趣的:(manager,String,C#,application,Class,vb)