How to run one instance of a c# WinForm application?

后端 未结 4 1870
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 19:27

I\'ve a C# application that displays a login form when launched and displays the main form after users are authenticated. I used Mutex to restrict that only one instance of

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 20:12

    If you are ok with a reference to Microsoft.VisualBasic, you can use its SingleInstance processing.

        [STAThread]
        static void Main(string[] args)
        {
            using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, "MyApp.SingleInstance.Mutex", out createdNew))
            {
                MainForm = new MainDlg();
                SingleInstanceApplication.Run(MainForm, StartupNextInstanceEventHandler);
            }
        }
    
        public static void StartupNextInstanceEventHandler(object sender, StartupNextInstanceEventArgs e)
        {
            MainForm.Activate();
        }
    
    public class SingleInstanceApplication : WindowsFormsApplicationBase
    {
        private SingleInstanceApplication()
        {
            base.IsSingleInstance = true;
        }
    
        public static void Run(Form f, StartupNextInstanceEventHandler startupHandler)
        {
            SingleInstanceApplication app = new SingleInstanceApplication();
            app.MainForm = f;
            app.StartupNextInstance += startupHandler;
            app.Run(Environment.GetCommandLineArgs());
        }
    }
    

提交回复
热议问题