What is the correct way to create a single-instance WPF application?

前端 未结 30 3176
耶瑟儿~
耶瑟儿~ 2020-11-21 05:14

Using C# and WPF under .NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance?

I kno

30条回答
  •  情话喂你
    2020-11-21 05:34

    Look at the folllowing code. It is a great and simple solution to prevent multiple instances of a WPF application.

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        Process thisProc = Process.GetCurrentProcess();
        if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
        {
            MessageBox.Show("Application running");
            Application.Current.Shutdown();
            return;
        }
    
        var wLogin = new LoginWindow();
    
        if (wLogin.ShowDialog() == true)
        {
            var wMain = new Main();
            wMain.WindowState = WindowState.Maximized;
            wMain.Show();
        }
        else
        {
            Application.Current.Shutdown();
        }
    }
    

提交回复
热议问题