我正在尝试使用 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;
}
}
}
MessageBox
“首次启动”的字样。MessageBox
,在同一个.exe文件再次双击。这应该会弹出“后续启动” MessageBox
。请注意,如果您关闭该应用程序,当您启动另一个实例时,您将再次看到“首次启动”消息。只有当有正在运行的另一个实例是,OnStartupNextInstance
将被调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句