WPF 避免重复启动程序

1.VS中右键App.xaml,【生成操作】选择为【Page】

2.修改App.xaml.cs文件如下:

using System;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using System.Windows;

namespace WpfDemo
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        [STAThread]
        static void Main()
        {
            var mutetx = new Mutex(true, "WpfDemo");
            if (!mutetx.WaitOne(TimeSpan.Zero, true))
            {
                return;
            }

            var container = new ServiceCollection();
            container.AddSingleton<MainWin>();
            var services= container.BuildServiceProvider();

            var app = new App();
            app.MainWindow = services.GetRequiredService<MainWin>();
            app.MainWindow.Visibility = Visibility.Visible;
            app.Run();
        }

        public App() 
        {
            InitializeComponent();
        }
    }
}

 

posted @ 2024-01-15 10:33  超级驼鹿  阅读(95)  评论(0编辑  收藏  举报
/*