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

WinUI 3(打包应用)如何处理文件激活及获取文件路径?

WinUI 3 中处理文件激活事件及获取文件路径

你已经正确配置了Package.appxmanifest中的文件关联,在WinUI 3中需要通过注册Activated事件来捕获文件激活请求,具体实现如下:

1. 在App.xaml.cs中捕获激活事件

WinUI 3的Microsoft.UI.Xaml.Application类没有可直接重写的OnFileActivated方法,需在应用启动时注册Activated事件:

using Windows.ApplicationModel.Activation;
using Windows.Storage;

namespace YourAppNamespace
{
    public partial class App : Application
    {
        private Window m_window;

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            // 注册Activated事件以监听文件激活
            this.Activated += OnAppActivated;

            m_window = new MainWindow();
            m_window.Activate();
        }

        private void OnAppActivated(object sender, WindowActivatedEventArgs args)
        {
            // 判断是否为文件激活类型
            if (args.Kind == ActivationKind.File)
            {
                FileActivatedEventArgs fileArgs = args as FileActivatedEventArgs;
                if (fileArgs?.Files?.Count > 0)
                {
                    // 获取激活的第一个文件
                    StorageFile activatedFile = fileArgs.Files[0] as StorageFile;
                    if (activatedFile != null)
                    {
                        string filePath = activatedFile.Path;
                        // 将文件路径传递给主窗口处理
                        if (m_window is MainWindow mainWindow)
                        {
                            mainWindow.ProcessActivatedFile(filePath);
                        }
                    }
                }
            }
        }
    }
}

2. 在主窗口中处理文件逻辑

在MainWindow.xaml.cs中添加方法接收并处理激活的文件:

using Microsoft.UI.Xaml.Controls;

namespace YourAppNamespace
{
    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
        }

        public void ProcessActivatedFile(string filePath)
        {
            // 这里实现你的.prxlvl文件加载逻辑
            // 示例:弹出对话框显示文件路径
            ContentDialog dialog = new ContentDialog
            {
                Title = "加载关卡文件",
                Content = $"已激活文件:{filePath}",
                CloseButtonText = "确认",
                XamlRoot = this.Content.XamlRoot
            };
            _ = dialog.ShowAsync();
        }
    }
}

关键说明

  • 确保引用必要的命名空间:Windows.ApplicationModel.Activation(处理激活事件)和Windows.Storage(操作文件)。
  • 如果是打包的WinUI 3桌面应用,上述逻辑同样适用,无需额外配置manifest之外的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:37:40