C#禁止程序重复打开

禁止程序被打开两次方法

方法一:亲测可用

在项目的第一个窗体的启动事件中 如form1_load() 中添加如下语句

        //判断是否重复打开
        public void check(object sender, EventArgs e)
        {
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("WMS_RFID");//获取指定的进程名   
            if (myProcesses.Length > 1) //如果可以获取到知道的进程名则说明已经启动
            {
                MessageBox.Show("程序已启动!");
                Application.Exit();              //关闭系统
            }
        }

 

====================================================================================================================

方法二 :未测试

在项目的启动引导文件 Program.cs中加入判断语句

using System.Linq;
using System.Windows.Forms;

namespace XiaoZhiSoft
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool isRuned;
            System.Threading.Mutex mutex = new System.Threading.Mutex(true, "OnlyRunOneInstance", out isRuned);
            if (isRuned)
            {

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                mutex.ReleaseMutex();
            }
            else
            {
                MessageBox.Show("程序已启动!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

 

posted @ 2017-08-28 10:06  zbchls  阅读(1842)  评论(1编辑  收藏  举报