Search code examples
c#.netmauifile-associationmaui-windows

File activation in MAUI


I want users to be able to open a file using my MAUI app. For example in Windows they could right-click on the file in File Explorer, choose my app in "open with" and then my app would open the file.

I have put file type associations in the Windows app manifest, and it does successfully launch my app when the file is opened by the user in File Explorer.

My problem is, how do I get notified that the reason my app was launched was because they want to open a file, and how do I get the file path?

If this was a regular UWP app and not a MAUI app, I could overload Application.OnFileActivated and handle it there. However I have not been able to find that in MAUI. link to MAUI source

Should I try to handle this by overloadng MauiWinUIApplication.OnLaunched for the Windows version of my app? Or do I have to add handlers via ConfigureLifecycleEvents? Or somewhere else?

I see that OnLaunched is being triggered when I try to open my app with the file, but a) args.UWPLaunchActivatedEventArgs.Kind is always ActivationKind.Launch and never ActivationKind.File and b) the file path doesn't appear in the LaunchActivatedEventArgs object anywhere. Obviously if nothing else I will need to get the file path somehow.


Solution

  • Overloading MauiWinUIApplication.OnLaunched in App.xaml.cs was the correct approach, but the args it gets are buggy (they never have ActivationKind.File and never include the path to the file). A workaround for this bug is to get the real args from another API.

    protected override void OnLaunched(LaunchActivatedEventArgs buggyArgs)
    {
        base.OnLaunched(buggyArgs);
    
        var goodArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
    
        switch (goodArgs.Kind)
        {
            case ExtendedActivationKind.File:
                var data = goodArgs.Data as IFileActivatedEventArgs;
                var paths = data.Files.Select(file => file.Path).ToArray();
                // Do something
                break;
        }
    }