C # winform can only allow one application (using a mutex)

In many application development process, we need to allow only one instance of the program, even if the connection came through a virtual desktop model, which is only one person running. Here is the code for the function, attention mutexName the system name, Global global, said that even by coming through the virtual desktop connection, it is only allowed to run again.

using System;
using System.Threading;
using System.Windows.Forms;

namespace WinformOneAppOnce
{
    static class Program
    {
		/// <summary>
		/// mutex互斥锁
		/// </summary>
		private static Mutex mutex = null;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
			GlobalMutex();
			Application.Run(new Form1());
        }

		private static void GlobalMutex()
		{
			bool createdNew = false;
			////系统名称,Global为全局,表示即使通过通过虚拟桌面连接过来,也只是允许运行一次
			string name = "WinformOneAppOnce1";
			try
			{
				mutex = new Mutex(initiallyOwned: false, name, out createdNew);
			}
			catch (Exception ex)
			{
				Console.Write(ex.Message);
				Thread.Sleep(1000);
				Environment.Exit(1);
			}
			if (createdNew)
			{
				Console.WriteLine("程序已启动");
				return;
			}
			MessageBox.Show("另一个窗口已在运行,不能重复运行。");
			Thread.Sleep(1000);
			Environment.Exit(1);
		}

	}
}

Published 126 original articles · won praise 21 · Views 150,000 +

Guess you like

Origin blog.csdn.net/xingkongtianyuzhao/article/details/103995938