You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WindowsAppSDK中无ProtocolActivatedEventArgs,协议激活处理遇问题

解决协议激活中找不到ProtocolActivatedEventArgs的问题

你遇到的Microsoft.Windows.AppLifecycle.ProtocolActivatedEventArgs不存在的问题,核心是对Windows App SDK的AppLifecycle API使用方式有误,以下是具体解决方法:

问题根源

Windows App SDK中,从AppInstance.GetActivatedEventArgs()获取的ActivatedEventArgs,需要通过GetAs<T>()方法转换为具体激活类型参数,而非直接强制转换。同时你可能混淆了UWP与Windows App SDK的命名空间,正确的协议激活参数类型位于Windows.ApplicationModel.Activation命名空间下。

解决步骤

  • 确认项目已安装Microsoft.WindowsAppSDK NuGet包,建议使用1.5及以上稳定版本。
  • 替换代码中错误的类型判断逻辑,用GetAs<T>()方法提取协议激活参数。
  • 移除对不存在的Microsoft.Windows.AppLifecycle.ProtocolActivatedEventArgs的引用,改用标准的Windows.ApplicationModel.Activation.ProtocolActivatedEventArgs。

修正后的代码

using Windows.ApplicationModel.Activation;

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    var activatedArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
    var e = args.UWPLaunchActivatedEventArgs;
    InitializeRootFrame(e);

    if (activatedArgs.Kind is ExtendedActivationKind.Launch)
    {
        if (!e.PrelaunchActivated)
        {
            if (RootFrame.Content == null)
            {
                RootFrame.Navigate(typeof(LoginPage), e.Arguments);
            }
            Window.Current.Activate();
        }
    }
    else // 非常规启动(如协议激活)
    {
        try
        {
            if (activatedArgs.Kind is ExtendedActivationKind.Protocol)
            {
                // 通过GetAs方法获取协议激活参数
                var protocolArgs = activatedArgs.GetAs<ProtocolActivatedEventArgs>();
                if (protocolArgs?.Uri != null)
                {
                    var queryParameters = System.Web.HttpUtility.ParseQueryString(protocolArgs.Uri.Query);
                    PocessQueryForToken(queryParameters);
                }
            }
        }
        catch (Exception)
        {
            // 按需添加异常处理逻辑
        }
        finally
        {
            if (RootFrame.Content == null)
            {
                RootFrame.Navigate(typeof(LoginPage));
            }
            Window.Current.Activate();
            HasLaunched = true;
        }
    }
    HasLaunched = true;
}

补充提示

如果是WinUI 3桌面应用,更规范的做法是将协议激活逻辑放在App.OnActivated方法中,避免在OnLaunched中混合处理多种激活类型;同时要确保已在Package.appxmanifest中注册对应协议声明,否则协议激活不会触发。

内容的提问来源于stack exchange,提问作者Muhammad Touseef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:22:45