欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF 应用程序单例启动类

程序员文章站 2022-07-13 22:23:34
...

 1、删除掉项目自动创建的App.xaml文件;

2、添加一个App.class文件;

3、实现代码如下:

using Microsoft.VisualBasic.ApplicationServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WpfTest
{
    class App
    {
        [STAThread]
        static void Main(string[] args)
        {
            //非单例启动
            //Application app = new Application();          
            //MainWindow win = new MainWindow();
            // app.Run(win);

            //单例启动
            SingleInstanceManager SingleInstance = new SingleInstanceManager();
            SingleInstance.Run(args);
        }
    }
    class SingleInstanceManager : WindowsFormsApplicationBase
    {
        SingleInstanceApplication app;

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

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            app = new SingleInstanceApplication();
            app.Run();
            return false;
        }

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

    class SingleInstanceApplication : Application
    {
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            MainWindow window = new MainWindow();
            window.Show();
        }

        public void Activate()
        {
            this.MainWindow.Show();
            this.MainWindow.Activate();
            this.MainWindow.WindowState = WindowState.Normal;
        }
    }
}