【整理】c# 中实现单实例应用程序的几种方法

来源:互联网 发布:辐射4 mac版下载 编辑:程序博客网 时间:2024/05/16 11:43

一、引用Microsoft.VisualBaisc.ApplicationServices实现

首先添加引用Microsoft.VisualBaisc,

再新建一个MyApplication类。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.VisualBasic.ApplicationServices;namespace Report{    /// <summary>     /// WindowsFormsApplicationBase位于Microsoft.VisualBasic.ApplicationServices命名空间     /// 也就是My里面的    /// </summary>     public class MyApplication : WindowsFormsApplicationBase     {         public MyApplication()         {             //设置只有一个应用程序实例             this.IsSingleInstance = true;         }          protected override void OnCreateMainForm()         {             //实例化主窗体             this.MainForm = new General();          }     }}

改造一下Program类,

    static class Program    {        /// <summary>        /// 应用程序的主入口点。        /// </summary>        [STAThread]        static void Main(string[] args)        {            MyApplication app = new MyApplication();            app.Run(args);        }    }

二、互斥体

改造一下Program类Main()

            bool blnIsRunning;            using (Mutex mutexApp = new Mutex(false, Assembly.GetExecutingAssembly().FullName, out   blnIsRunning))            {                if (blnIsRunning)                {                    Application.EnableVisualStyles();                    Application.SetCompatibleTextRenderingDefault(false);                    Application.Run(new General());                }            }