首页 > 代码库 > Winfrom 程序不能重复启动

Winfrom 程序不能重复启动

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Demo
{
    static class Program
    {
        /// <summary>
        /// 用于判断程序是否有重复启动的互斥量
        /// </summary>
        static System.Threading.Mutex _mutex;

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
           
            //是否可以打开新进程
            bool createNew;

            /// 获取程序集Guid作为唯一标识,禁止程序重复启动
            Attribute guid_attr = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute));
            string guid = ((GuidAttribute)guid_attr).Value;
            _mutex = new System.Threading.Mutex(true, guid, out createNew);

            if (false == createNew)
            {
                MessageBox.Show("程序已在本机运行,不能重复运行!", "系统消息");
                Application.Exit();
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                _mutex.ReleaseMutex();    
                Application.Run(new FrmMain());
            }
        }
    }
}

 

Winfrom 程序不能重复启动