一、添加引用Microsoft.VisualBasic
二、添加新类,单实例应用程序包装器SingleInstanceApplicationWrapper类,这里我将App.xaml的启动方式删除,使用自己创建的启动代码,下面附上。
代码语言:javascript复制using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace single
{
class SingleInstanceApplicationWrapper:Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
public SingleInstanceApplicationWrapper()
{
//是否允许单实例
this.IsSingleInstance = true;
}
private WpfApp app;
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
//return base.OnStartup(eventArgs);
app = new WpfApp();
app.Run();
return false;
}
//打开下个实例时做的操作
protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
app.showWindow();
}
}
}
代码语言:javascript复制using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace single
{
class WpfApp:System.Windows.Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
base.OnStartup(e);
showWindow();
}
public void showWindow()
{
MainWindow win = new MainWindow();
win.Show();
}
}
}
代码语言:javascript复制using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace single
{
class Startup
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceApplicationWrapper wrapper = new SingleInstanceApplicationWrapper();
wrapper.Run(args);
}
}
}
这样你再程序启动后观察任务管理器,不论打开几个程序都将只有一个实例