WPF-单实例化程序

一、添加引用Microsoft.VisualBasic

这里写图片描述
二、添加新类,单实例应用程序包装器SingleInstanceApplicationWrapper类,这里我将App.xaml的启动方式删除,使用自己创建的启动代码,下面附上。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace single
{
    class SingleInstanceApplicationWrapper:Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
    {
        public SingleInstanceApplicationWrapper()
        {
            //是否允许单实例
            this.IsSingleInstance = true;
        }
        private WpfApp app;
        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
        {
            //return base.OnStartup(eventArgs);
            app = new WpfApp();
            app.Run();
            return false;
        }
        //打开下个实例时做的操作
        protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
        {
            base.OnStartupNextInstance(eventArgs);
            app.showWindow();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace single
{
    class WpfApp:System.Windows.Application
    {
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            base.OnStartup(e);
            showWindow();
        }

        public void showWindow()
        {
            MainWindow win = new MainWindow();
            win.Show();

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace single
{
    class Startup
    {
        [STAThread]
        public static void Main(string[] args)
        {
            SingleInstanceApplicationWrapper wrapper = new SingleInstanceApplicationWrapper();
            wrapper.Run(args);

        }
    }
}

这样你再程序启动后观察任务管理器,不论打开几个程序都将只有一个实例

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/80620348