【问题标题】:URI start of MAUI Windows app creates a new instance. I need to have only one instance of appMAUI Windows 应用程序的 URI 开始创建一个新实例。我只需要一个应用程序实例
【发布时间】:2022-10-24 02:16:37
【问题描述】:

我可以使用 URI 启动我的 Windows MAUI 应用程序,并且我可以获取 URI 本身。但是,似乎正在创建应用程序的新实例。这对我来说并不理想——如果我的应用程序已经在运行,我想使用那个实例。

我为 Xamarin.Forms 应用程序做了类似的事情。我在 Application 类中覆盖 OnActivated。

回复:我的 MAUI 应用程序,我什至不清楚问题是我如何完成 package.appxmanifest 中的“协议”,还是我如何响应生命周期事件。

【问题讨论】:

    标签: windows maui winui-3 winui


    【解决方案1】:

    默认行为是运行应用程序的多个实例。您可以按照this blog 帖子中的建议,通过使用Main 方法定义自定义类来使应用程序成为单实例:

    [STAThread]
    static async Task Main(string[] args)
    {
        WinRT.ComWrappersSupport.InitializeComWrappers();
        bool isRedirect = await DecideRedirection();
        if (!isRedirect)
        {
            Microsoft.UI.Xaml.Application.Start((p) =>
            {
                var context = new DispatcherQueueSynchronizationContext(
                    DispatcherQueue.GetForCurrentThread());
                SynchronizationContext.SetSynchronizationContext(context);
                new App();
            });
        }
        return 0;
    }
    
    private static async Task DecideRedirection()
    {
        bool isRedirect = false;
        AppActivationArguments args = AppInstance.GetCurrent().GetActivatedEventArgs();
        ExtendedActivationKind kind = args.Kind;
        AppInstance keyInstance = AppInstance.FindOrRegisterForKey("randomKey");
    
        if (keyInstance.IsCurrent)
        {
            keyInstance.Activated += OnActivated;
        }
        else
        {
            isRedirect = true;
            await keyInstance.RedirectActivationToAsync(args);
        }
        return isRedirect;
    }
    

    GitHub 上有一个开放的suggestion 来简化此过程。

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2012-10-30
      • 2011-08-30
      • 2014-12-21
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多