OnStartupNextInstance不会被调用

问题描述 投票:-1回答:2

我想建立使用C#的单个实例WPF应用程序。我跟着this answer创建以下应用程序。然而,OnStartupNextInstance功能不会被调用,不管有多少次我重新启动相同的应用程序(双击* .exe文件)。

有没有在调试输出打印异常或任何东西。

有没有人有一个实例WPF应用程序使用这种方法的工作?我缺少的是在这里吗?

using Microsoft.VisualBasic.ApplicationServices;
using System;
using System.Windows;

namespace WpfApp1
{
    public class EntryPoint
    {
        [STAThread]
        public static void Main(string[] args)
        {
            var man = new SingleInstanceManager();
            man.Run(args);
        }
    }

    public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
    {
        public SingleInstanceManager()
        {
            IsSingleInstance = true;
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
        {
            MessageBox.Show("First time launch");
            var app = new App();
            app.InitializeComponent();
            app.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            MessageBox.Show("Subsequent launch");
            base.OnStartupNextInstance(eventArgs);
            eventArgs.BringToForeground = true;
        }
    }
}
c# wpf windows
2个回答
0
投票
  • 构建应用程序。
  • 您在解决方案资源管理器在Visual Studio项目上右键单击,然后选择“在资源管理器中打开文件夹”。
  • 浏览到bin /调试(或斌/释放,如果你建在释放模式的应用程序)文件夹。
  • 在双击可执行文件(.exe文件)。然后,您应该看到一个MessageBox说:“第一次发射”。
  • 现在,无需关闭MessageBox,在相同的.exe再次双击。这应该弹出“随后推出的” MessageBox

请注意,如果您关闭应用程序,你将再次看到“第一时间推出”弹出消息,当您启动另一个实例。只有当有正在运行的OnStartupNextInstance将被称为另一个实例。


0
投票

你是不是在SingleInstanceManager设置MainForm中,你不需要new App().Run()

尝试:

    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        public SingleInstanceManager()
        {
            IsSingleInstance = true;
            MainForm = new MyMainForm();
        }

        protected override bool OnStartup(StartupEventArgs eventArgs)
        {
            MessageBox.Show("First time launch");
            return base.OnStartup(eventArgs);
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            MessageBox.Show("Subsequent launch");
            base.OnStartupNextInstance(eventArgs);
            eventArgs.BringToForeground = true;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.