[C#] 单实例运行

VB.net 如果需要单实例运行,只要在其属性中选中一个复选框就OK了,简单得不能再简单了。。。

在 C# 中,天生不支持单实例运行,如果想要单实例,处理起来很复制。
简单点的有 查找进程信息、线程同步等。用起来很不爽。

在 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

打开其中的 csharp 文件夹下的工程,关键部分在 App.cs 文件内,这个是程序入口所在。

看他 引用了
using Microsoft.VisualBasic.ApplicationServices;
头文件,呵呵,看来是调用 VB.net 的函数类库实现的。PS:记得引用“Microsoft.VisualBasic”库哦,不然会抱错的。

他给的 App.cs 貌似不是 普通窗体应用程序的。。需要改动一下。我的修改如下。

============================================================================
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            SingleInstanceManager manager = new SingleInstanceManager();//单实例管理器
            manager.Run(new string[]{});   
            //Application.Run(new frmMain()); //屏蔽掉了以前的加载头
        }

        // 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
        public class SingleInstanceManager : WindowsFormsApplicationBase
        {
            frmMain app;

            public SingleInstanceManager()
            {
                this.IsSingleInstance = true;
            }

            protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
            {
                // First time app is launched
                //app = new SingleInstanceApplication();
                //app.Run();
                app = new frmMain();//改为自己的程序运行窗体
                Application.Run(app);

                return false;
            }

            protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
            {
                // Subsequent launches
               
                base.OnStartupNextInstance(eventArgs);
                app.Activate();
                MessageBox.Show(Application.ProductName + " 已经在运行了,不能重复运行。", "确定", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);//给个对话框提示
            }
        }
    }

posted on 2010-02-21 16:42  BoneKing  阅读(664)  评论(0编辑  收藏  举报