C# OnStartupNextInstance未被调用
我正在尝试使用c#构建一个单实例WPF应用程序。我跟随创建以下应用程序。但是,无论我重新启动同一应用程序多少次(双击*.exe文件),OnStartupNextInstance函数都不会被调用 调试输出中没有异常或任何打印内容 是否有人使用这种方法使用单个实例WPF应用程序?我错过了什么C# OnStartupNextInstance未被调用,c#,wpf,windows,C#,Wpf,Windows,我正在尝试使用c#构建一个单实例WPF应用程序。我跟随创建以下应用程序。但是,无论我重新启动同一应用程序多少次(双击*.exe文件),OnStartupNextInstance函数都不会被调用 调试输出中没有异常或任何打印内容 是否有人使用这种方法使用单个实例WPF应用程序?我错过了什么 using Microsoft.VisualBasic.ApplicationServices; using System; using System.Windows; namespace WpfApp1 {
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;
}
}
}
- 构建您的应用程序李>
- 在Visual Studio的解决方案资源管理器中右键单击项目,然后选择“在文件资源管理器中打开文件夹”李>
- 浏览到bin/Debug(或bin/Release,如果在发布模式下构建应用程序)文件夹
- 双击可执行文件(.exe)。然后您会看到一个
,上面写着“首次启动”消息框
- 现在,在不关闭
消息框的情况下,再次双击相同的.exe。这将弹出“后续启动”消息框
请注意,如果关闭应用程序,则在启动另一个实例时,将再次看到“First time launch”(首次启动)消息弹出。只有当当前有另一个实例正在运行时,才会调用
OnStartupNextInstance
。您没有在SingleInstanceManager中设置MainForm,并且不需要new App().Run()
尝试:
在您的链接中,它建议使用一种方法
public void Activate()
,该方法激活主窗口(并在OnStartupNextInstance
中调用),这是否相关?此外,您还可以尝试在启动下一个实例的的第一行上放置断点,并使用调试模式检查代码是否到达该位置。您确定调试的实例正确吗?OnStartupNextInstance()
方法仅在原始进程中调用,而不是在新进程中调用。注意MessageBox.Show()
。您应该看到启动后续实例的消息框,并且您发布的代码中没有任何内容表明会发生任何不同的情况。您确定您发布的代码实际上就是您正在运行的代码吗?@KeyurPATEL WPF app没有激活功能:(@PeterDuniho这正是我正在运行的代码。应用程序对象是一个WPF应用程序,它的StartupUri设置为MainWindow。我确实看到MainWindow显示在MessageBox之后。我还设置了断点,并使用Visual Studio中的Debug>New Instance菜单逐行检查每一个新实例和后续实例发布的代码。我无法编辑解释昨晚代码不起作用的原因。但是,今天早上,它工作得很好。在重试之前,我确实在早上重新启动了我的计算机。也许这有帮助。这很好,但从不同文件夹调用的同一个EXE不应被视为单个实例。我们如何修复它?我怀疑这需要您自己的全局互斥体检查WindowsFormsApplicationBase不直接支持。可能由运行时业务逻辑决定不同的应用程序路径/版本/哈希是否为同一实例(例如:更新应用程序,第二个实例仅在第一个为UI时为命令行,等等)。您可以浏览WindowsFormsApplicationBase中的代码,并实现自己的:
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;
}
}