只允许程序运行一次的代码

来源:互联网 发布:淘宝网裤子piku 编辑:程序博客网 时间:2024/05/17 03:24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
namespace RunOnce
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool createNew = false;


            using (new Semaphore(0, 1, "MyAppIdentify", out createNew))
            {
                if (createNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }
                else
                {
                    MessageBox.Show("已经有程序在运行!");
                }


            }
        }
    }
}