WPF实现只启动一个程序实例,第二次启动,激活该程序实例,或提示:该程序已运行!
1,删除App.xaml中的 StartupUri=“MainWindow” 语句。
2,新建SingleInstanceWrapper包装器类
namespace Endeavour
{
class SingleInstanceWrapper:Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
private App a;
public SingleInstanceWrapper()
{
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
a = new App();
//App.InitializeComponent();
a.Run();
return false;
}
protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
a.Activate();
//a.Shutdown();
}
}
}
3,修改App.xaml.cs
namespace Endeavour
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private MainWindow mainWindow;
public App()
{
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
//App.Current = this;
mainWindow = new MainWindow();
mainWindow.Show();
}
public void Activate()
{
mainWindow.WindowState = WindowState.Maximized;
mainWindow.Show();
//MessageBox.Show("该程序已运行,请双击右下角任务栏将其唤出!");
}
private void Application_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
}
private void Application_Startup(object sender, StartupEventArgs e)
{
}
private void Application_Exit(object sender, ExitEventArgs e)
{
}
}
}
4,修改\obj\Debug下的App.g.cs和App.g.i.cs两个文件
修改后的Main函数为:
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main(string[] args) {
//Endeavour.App app = new Endeavour.App();
//app.Run();
SingleInstanceWrapper s = new SingleInstanceWrapper();
s.Run(args);
}