Search code examples
c#filewinui-3filehandlerwindows-app-sdk

How to handle activation through files in WinUI 3 (Packaged)?


I want to define a filetype to open in my app and have already gotten this far: I added this to my Package.appxmanifest inside the Application tag:

<Extensions>
  <uap:Extension Category="windows.fileTypeAssociation">
    <uap:FileTypeAssociation Name="pyrux-level">
      <uap:SupportedFileTypes>
        <uap:FileType>.prxlvl</uap:FileType>
      </uap:SupportedFileTypes>
      <uap:DisplayName>Pyrux Level</uap:DisplayName>
      <uap:EditFlags OpenIsSafe="true"/>
    </uap:FileTypeAssociation>
  </uap:Extension>
</Extensions>

This already registers the App as handler for the filetype and therefore opens it.

However, I am not sure how to handle the file once the app is open. I found a suggestion on the UWP documentation stating to use:

protected override void OnFileActivated(FileActivatedEventArgs args){}

However, I don't have a suitable method to override (guessing its due to the other API WinUI 3 uses compared to the normal UWP stuff...)

Can someone help me out on how to handle that event/figure out the path for the file opened? Thank you in advance!


Solution

  • According to the docs, instead of OnFileActivated, you use OnLaunched.

    Can you try this?

    using Microsoft.UI.Xaml;
    using Microsoft.Windows.AppLifecycle;
    using System.Linq;
    using Windows.ApplicationModel.Activation;
    using Windows.Storage;
    
    namespace Example;
    
    public partial class App : Application
    {
        private Window? _window;
    
        public App()
        {
            this.InitializeComponent();
        }
    
        protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
        {
            AppActivationArguments appActivationArguments = AppInstance.GetCurrent().GetActivatedEventArgs();
    
            if (appActivationArguments.Kind is ExtendedActivationKind.File &&
                appActivationArguments.Data is IFileActivatedEventArgs fileActivatedEventArgs &&
                fileActivatedEventArgs.Files.FirstOrDefault() is IStorageFile storageFile)
            {
                // Do something with the file...
            }
    
            _window = new MainWindow();
            _window.Activate();
        }
    }