OnStartupNextInstance 不会被调用

相信2014

我正在尝试使用 c# 构建一个单实例 WPF 应用程序。我按照这个答案来创建以下应用程序。但是,无论我重新启动同一个应用程序多少次(双击 *.exe 文件), OnStartupNextInstance 函数都不会被调用。

调试输出中没有任何异常或任何打印内容。

有没有人有使用这种方法工作的单实例 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;
        }
    }
}
毫米8
  • 构建您的应用程序。
  • 在 Visual Studio 的解决方案资源管理器中右键单击您的项目,然后选择“在文件资源管理器中打开文件夹”。
  • 浏览到 bin/Debug(或 bin/Release,如果您在发布模式下构建应用程序)文件夹。
  • 双击可执行文件 (.exe)。然后,您应该会看到MessageBox“首次启动”的字样。
  • 现在,不关闭MessageBox,在同一个.exe文件再次双击。这应该会弹出“后续启动” MessageBox

请注意,如果您关闭该应用程序,当您启动另一个实例时,您将再次看到“首次启动”消息。只有当有正在运行的另一个实例是,OnStartupNextInstance将被调用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章