1

I have a .Net Maui application that runs on iOS, Android and Windows and receives push notifications.

On Windows, when I click a notification nothing happens.

I would like to "raise" the active instance that is opened, something like window.Focus() when a notification is clicked.

The way it was made in Xamarin Forms:

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active.
    if (rootFrame == null)
    {
        // Create a Frame to act as the navigation context and navigate to the first page.
        rootFrame = new Frame();

        rootFrame.NavigationFailed += OnNavigationFailed;

        if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application.
        }

        // Place the frame in the current Window.
        Window.Current.Content = rootFrame;
    }

    if (rootFrame.Content == null)
    {
        // When the navigation stack isn't restored navigate to the first page,
        // configuring the new page by passing required information as a navigation
        // parameter.
        rootFrame.Navigate(typeof(MainPage), e.Arguments);
    }

    // Ensure the current window is active.
    Window.Current.Activate();
}

I found examples but in all of them the App class inherits from Application which is not the case on Maui since it inherits from MauiWinUIApplication.

My App.xamls.cs:

public partial class App : MauiWinUIApplication
{
    /// <summary>
    /// Initializes the singleton application object.  This is the first line of authored code
    /// executed, and as such is the logical equivalent of main() or WinMain().
    /// </summary>
    /// 
    private readonly SingleInstanceDesktopApp _singleInstanceApp;
    LaunchActivatedEventArgs incomeArgs;

    public App()
    {
        this.InitializeComponent();

        _singleInstanceApp = new SingleInstanceDesktopApp("GIKI");
        _singleInstanceApp.Launched += OnSingleInstanceLaunched;
    }

    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    protected override async void OnLaunched(LaunchActivatedEventArgs args)
    {
        incomeArgs = args;
        _singleInstanceApp.Launch(args.Arguments);
    }

    private void OnSingleInstanceLaunched(object? sender, SingleInstanceLaunchEventArgs e)
    {
        try
        {
            if (e.IsFirstLaunch)
            {
                base.OnLaunched(incomeArgs);
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex}");
        }
    }

    void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
    {
        throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
    }
    private void OnSuspending(object sender, SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();
        //TODO: Save application state and stop any background activity
        deferral.Complete();
    }
}

The OnSingleINstanceLauched method is working. What next, on "else" to show the window in case it is in background, for example?

2
  • Click on MauiWinUIApplication. F12 to go to definition. That should open a window showing declaration of MauiWinUIApplication. Notice that it inherits from Application. So, it is still an Application. AFAIK, You should be able to use the Application examples you found. Commented Nov 25, 2022 at 19:00
  • I try to use the code in the maui. And the Window.Current always be null. In addition, all the properties of the MauiWinUIApplication are null. But when I called the base.OnLaunched, this.Application will have value. And there is a api named AppInstance.GetCurrent();, you may can use it do something. Commented Nov 28, 2022 at 8:52

2 Answers 2

0

Not diving into your code, instead of "protected override void OnLaunched(LaunchActivatedEventArgs e)" you could use Maui

builder.ConfigureLifecycleEvents(AppLifecycle =>
        {

#if WINDOWS

            AppLifecycle.AddEvent<OnLaunched>("OnLaunched", (Application application, LaunchActivatedEventArgs args) =>
            {

            //do your stuff

            });

#endif

        });
Sign up to request clarification or add additional context in comments.

Comments

0

After reviewing several incomplete leads including some from Xamarin Forms this was what I found to work.

My particular use case was restoring focus to my app after authenticating using easy auth via protocol activation from a web page. It also resolved a problem I had with PopModalAsync failing to navigate back from a Login page.

In MauiProgram.cs:

    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();

            builder
                .UseMauiApp<App>()
#if WINDOWS
                .ConfigureLifecycleEvents(events =>
                {                    
                    events.AddWindows(windows => windows.OnWindowCreated(window =>
                    {
                        YourNamespace.WinUI.Program.CurrentWindow = window as MauiWinUIWindow;
                    }));
                })
#endif

Then in Windows\Platform\Program.cs (This could also be in Windows\Platform\App.xaml.cs if you did not implement Program.cs)

public class Program
{
    public static MauiWinUIWindow? CurrentWindow { get; set; }

    public static void ActivateApplication()
    {
        if (Program.CurrentWindow != null)
        {
            Program.SetForegroundWindow(Program.CurrentWindow.WindowHandle);
        }
    }

    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

Now you can call YourNamespace.WinUI.Program.ActivateApplication() from any place in your Windows MAUI app.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.