我想建立使用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;
}
}
}
MessageBox
说:“第一次发射”。MessageBox
,在相同的.exe再次双击。这应该弹出“随后推出的” MessageBox
。请注意,如果您关闭应用程序,你将再次看到“第一时间推出”弹出消息,当您启动另一个实例。只有当有正在运行的OnStartupNextInstance
将被称为另一个实例。
你是不是在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;
}
}