wpf 程序 启动唯一一个进程,避免多次打开

使用WindowsFormsApplicationBase

首先在项目中创建一个启动类

    class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            SingleInstanceManager manager = new SingleInstanceManager();
            manager.Run(args);
        }
    }

    /// <summary>
    /// 单例进程
    /// </summary>
    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        App app;

        public SingleInstanceManager()
        {
            this.IsSingleInstance = true;
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            // First time app is launched
            app = new App();
            app.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // Subsequent launches
            base.OnStartupNextInstance(eventArgs);
            app.Activate();
        }
    }

然后再我们原先的app中,去掉Application_Startup事件的引用,使用重写的 protected override void OnStartup(StartupEventArgs e)

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
           
          
                LoadComponent(this, new Uri("App.xaml", System.UriKind.Relative));


            MainWindow window = new MainWindow();
            window.Show();
        }

 

app中添加激活方法

        public void Activate()
        {
            if (this.MainWindow != null)
            {
                this.MainWindow.Show();
                this.MainWindow.Activate();
            }
        }

 

 

这个时候运行报错会提示重复的main入口

右键项目属性 应用程序 启动对象更改你添加的入口类

至此,应用程序就会始终以单例的形式打开了!

 

posted @ 2022-04-24 17:31  一条大河啊波浪宽啊  阅读(834)  评论(0编辑  收藏  举报