只允许允许一个程序实例,即使是通过虚拟桌面方式连接过来的,也是只允许一个人运行。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading ;

namespace PMS   
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //只允许允许一个程序实例,即使是通过虚拟桌面方式连接过来的,也是只允许一个人运行。
            GlobalMutex();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frm_onlineDevices());
        }

        private static Mutex mutex = null;
        private static void GlobalMutex()
        {
            //是否第一次创建mutex
            bool newMutexCreated = false;
            string mutexName = "Global\\" + "PMS";//系统名称,Global为全局,表示即使通过通过虚拟桌面连接过来,也只是允许运行一次
            try
            {
                mutex = new Mutex(false, mutexName, out newMutexCreated);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                Thread.Sleep(1000);
                Environment.Exit(1);
            }
 
            //第一次创建mutex
            if (newMutexCreated)
            {
            }
            else
            {
                MessageBox.Show("另一个窗体已在运行,不能重复运行。", "系统提示", MessageBoxButtons.OK);
                Thread.Sleep(1000);
                Environment.Exit(1);
            }
        }
    }
}

原文地址:https://www.cnblogs.com/wpf123/p/2052907.html