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

后端 未结 4 1876
佛祖请我去吃肉
佛祖请我去吃肉 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:13

    I've made some small changes:

    
    namespace CSMutex
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                bool mutexCreated=true;
                using(Mutex mutex = new Mutex(true, "eCS", out mutexCreated))
                {
                    if (mutexCreated)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Login loging = new Login();
                        Application.Run(loging);
                        Application.Run(new Main() { UserName = loging.UserName });
                    }
                    else
                    {
                        Process current = Process.GetCurrentProcess();
                        foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                        {
                            if (process.Id != current.Id)
                            {
                                MessageBox.Show("Another instance of eCS is already running.", "eCS already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                //SetForegroundWindow(process.MainWindowHandle);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    

    That works as expected - i.e. even when Login form is closed (and the main application form is started) it doesn't let user run the application once again. I've decided not to create Main from within Login (this is I believe how you application works) and instead I am passing parameter to Main. I have also made some small change to Login so it has UserName propert (same as Main).

提交回复
热议问题