前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPF-单实例化程序

WPF-单实例化程序

作者头像
MaybeHC
发布2024-04-23 18:18:32
590
发布2024-04-23 18:18:32
举报
文章被收录于专栏:技术之路技术之路

一、添加引用Microsoft.VisualBasic

这里写图片描述
这里写图片描述

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

代码语言:javascript
复制
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();
        }
    }
}
代码语言:javascript
复制
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();

        }
    }
}
代码语言:javascript
复制
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);

        }
    }
}

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档