虽然上面我们简单介绍了WPF应用的生命周期,但是默认情况下我们可以打开一个应用程序多个实例,例如你双击一个exe多次。当然有些时候这么做会带来很多好处,但是有时我们又不希望这么做,要避免这个问题其实很简单,同WinForm中单实例运行一个应用是一样的,我们只需要在应用程序启动时创建一个”排他锁”,修改App.xaml.cs如下:
using System;
using System.Windows;
using System.Threading;
namespace WPFLifeCycle
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
Mutex mutex=null;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
bool createdNew = false;
mutex = new Mutex(true, "WPFLifeCycle",out createdNew);
if (!createdNew)
{
MessageBox.Show("程序正在运行中,无法启动另一个实例!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
this.Shutdown();
}
}
}
}
此时如果我们已经运行了WPFLifeCycle.exe,当再双击此应用则会给出提示: