Run one instance from the application

前端 未结 7 950
盖世英雄少女心
盖世英雄少女心 2020-12-16 06:49

I have a windows application (C#) and i need to configure it to run one instance from the application at the time , It means that one user clicked the .exe file and the appl

7条回答
  •  时光取名叫无心
    2020-12-16 07:22

    I found this code, it's work!

     /// 
            /// The main entry point for the application.
            /// Limit an app.to one instance
            /// 
            [STAThread]
            static void Main()
            {
                //Mutex to make sure that your application isn't already running.
                Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
                try
                {
                    if (mutex.WaitOne(0, false))
                    {
                        // Run the application
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new Form1());
                    }
                    else
                    {
                        MessageBox.Show("An instance of the application is already running.",
                            "An Application Is Running", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Application Error 'MyUniqueMutexName'", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                finally
                {
                    if (mutex != null)
                    {
                        mutex.Close();
                        mutex = null;
                    }
                }
            }
    

提交回复
热议问题