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

前端 未结 30 3200
耶瑟儿~
耶瑟儿~ 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:30

    A time saving solution for C# Winforms...

    Program.cs:

    using System;
    using System.Windows.Forms;
    // needs reference to Microsoft.VisualBasic
    using Microsoft.VisualBasic.ApplicationServices;  
    
    namespace YourNamespace
    {
        public class SingleInstanceController : WindowsFormsApplicationBase
        {
            public SingleInstanceController()
            {
                this.IsSingleInstance = true;
            }
    
            protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
            {
                e.BringToForeground = true;
                base.OnStartupNextInstance(e);
            }
    
            protected override void OnCreateMainForm()
            {
                this.MainForm = new Form1();
            }
        }
    
        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                string[] args = Environment.GetCommandLineArgs();
                SingleInstanceController controller = new SingleInstanceController();
                controller.Run(args);
            }
        }
    }
    

提交回复
热议问题