C# winform 一次只能允许一个应用(使用mutex)

在很多应用程序开发过程中,需要只允许一个程序实例,即使是通过虚拟桌面方式连接过来的,也是只允许一个人运行。下面是实现该功能的代码,注意mutexName 为系统名称,Global为全局,表示即使通过通过虚拟桌面连接过来,也只是允许运行一次。

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);
		}

	}
}

发布了126 篇原创文章 · 获赞 21 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/xingkongtianyuzhao/article/details/103995938