wpf单实例运行

时间:2023-03-08 16:12:47

默认情况下我们可以打开一个应用程序多个实例,例如你双击一个exe多次。当然有些时候这么做会带来很多好处,但是有时我们又不希望这么做,要避免这个问题其实很简单,同WinForm中单实例运行一个应用是一样的,我们只需要在应用程序启动时创建一个"排他锁",修改App.xaml.cs如下:

  1. using System;
  2. using System.Windows;
  3. using System.Threading;
  4. namespace WPFLifeCycle
  5. {
  6. /// <summary>
  7. /// Interaction logic for App.xaml
  8. /// </summary>
  9. public partial class App : Application
  10. {
  11. Mutex mutex=null;
  12. protected override void OnStartup(StartupEventArgs e)
  13. {
  14. base.OnStartup(e);
  15. bool createdNew = false;
  16. mutex = new Mutex(true, "WPFLifeCycle",out createdNew);
  17. if (!createdNew)
  18. {
  19. MessageBox.Show("程序已启动!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
  20. this.Shutdown();
  21. }
  22. }
  23. }
  24. }

参考WPF系列之应用程序生命周期