C#中防止程序多次运行

C#中如何防止程序多次运行?只要在程序入口点函数Main()中的开始部分添加如注释部分的代码,就能快捷实现。
 
示例代码如下:

using System;

using System.Collections.Generic;

using System.Windows.Forms;

 

namespace WindowsApplication1

{

    static class Program

    {

        /// <summary>

        /// 应用程序的主入口点。

        /// </summary>

        [STAThread]

        static void Main()

        {

            //防止程序多次运行的代码

            string MName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;

            string PName = System.IO.Path.GetFileNameWithoutExtension(MName);

            System.Diagnostics.Process[] myProcess = System.Diagnostics.Process.GetProcessesByName(PName);

            if (myProcess.Length > 1)

            {

                MessageBox.Show("本程序一次只能运行一个实例!", "提示", MessageBoxButtons.OK,MessageBoxIcon.Information);

                return;

            }

 

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new Form1());

        }

    }

}

原文地址:https://www.cnblogs.com/ysz12300/p/5494716.html