Skip to content
Closed
32 changes: 32 additions & 0 deletions src/Controls/samples/Controls.Sample/MauiProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics.Metrics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Maui.Controls.Sample.Controls;
Comment on lines +7 to 8
using Maui.Controls.Sample.Pages;
Comment on lines 5 to 9
using Maui.Controls.Sample.Services;
Expand All @@ -29,6 +30,8 @@
#if ANDROID
using Android.Gms.Common;
using Android.Gms.Maps;
#elif WINDOWS
using Microsoft.Windows.AppLifecycle;
#endif

namespace Maui.Controls.Sample
Expand Down Expand Up @@ -286,6 +289,7 @@ static string GetTags(IEnumerable<KeyValuePair<string, object?>> tags) =>
events.AddWindows(windows => windows
// .OnPlatformMessage((a, b) =>
// LogEvent(nameof(WindowsLifecycle.OnPlatformMessage)))
.OnAppActivation((application, args) => HandleWindowsAppActivation(application, args))
.OnActivated((a, b) => LogEvent(nameof(WindowsLifecycle.OnActivated)))
.OnClosed((a, b) => LogEvent(nameof(WindowsLifecycle.OnClosed)))
.OnLaunched((a, b) => LogEvent(nameof(WindowsLifecycle.OnLaunched)))
Expand All @@ -310,6 +314,34 @@ static bool LogEvent(string eventName, string? type = null)
Debug.WriteLine($"Lifecycle event: {eventName}{(type == null ? "" : $" ({type})")}");
return true;
}

#if WINDOWS
static bool HandleWindowsAppActivation(Microsoft.UI.Xaml.Application application, AppActivationArguments args)
{
LogEvent(nameof(WindowsLifecycle.OnAppActivation), args.Kind.ToString());

// This sample opts into single-instancing from the MAUI lifecycle callback
// instead of a custom Program.cs entry point.
var keyInstance = AppInstance.FindOrRegisterForKey("Maui.Controls.Sample");

if (!keyInstance.IsCurrent)
{
// The WinAppSDK single-instance guidance redirects the activation and then
// terminates the losing instance immediately. Using Kill here avoids leaving
// a headless process around that can continue to hold build outputs open.
keyInstance.RedirectActivationToAsync(args).AsTask().GetAwaiter().GetResult();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 AI-Generated Review (multi-model)

[major] Async and Threading Safety — Same blocking pattern as the library code: keyInstance.RedirectActivationToAsync(args).AsTask().GetAwaiter().GetResult() runs inside HandleWindowsAppInstanceActivated, invoked as a WindowsLifecycle.OnAppInstanceActivated handler on the UI thread (either directly from OnLaunched or dispatched from MauiWinUIApplication.HandleAppInstanceActivated). This is presented to app authors as recommended single-instancing boilerplate, but it teaches the same deadlock/hang-prone anti-pattern flagged in the product code instead of awaiting the redirect.

Process.GetCurrentProcess().Kill();
return true;
Comment thread
mattleibow marked this conversation as resolved.
Resolved
}

if (Application.Current?.Windows.FirstOrDefault() is Window window)
// Redirected activations can arrive off the UI thread, so hop through the
// MAUI window dispatcher before re-activating the existing window.
window.Dispatcher.Dispatch(() => Application.Current.ActivateWindow(window));

return false;
}
#endif
});

// Adapt to dual-screen and foldable Android devices like Surface Duo, includes TwoPaneView layout control
Expand Down
5 changes: 4 additions & 1 deletion src/Core/src/LifecycleEvents/Windows/WindowsLifecycle.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
namespace Microsoft.Maui.LifecycleEvents
using Microsoft.Windows.AppLifecycle;

namespace Microsoft.Maui.LifecycleEvents
{
public static class WindowsLifecycle
{
public delegate bool OnAppActivation(UI.Xaml.Application application, AppActivationArguments args);
public delegate void OnActivated(UI.Xaml.Window window, UI.Xaml.WindowActivatedEventArgs args);
Comment on lines 5 to 8

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR description and metadata refer to a new OnAppActivation(...) hook, but the implementation introduces OnAppInstanceActivated(...) instead. Please update the PR description (or rename the API) so the documented public surface matches the code that will ship.

Copilot uses AI. Check for mistakes.
public delegate void OnClosed(UI.Xaml.Window window, UI.Xaml.WindowEventArgs args);
public delegate void OnLaunched(UI.Xaml.Application application, UI.Xaml.LaunchActivatedEventArgs args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{
public static class WindowsLifecycleBuilderExtensions
{
public static IWindowsLifecycleBuilder OnAppActivation(this IWindowsLifecycleBuilder lifecycle, WindowsLifecycle.OnAppActivation del) => lifecycle.OnEvent(del);
public static IWindowsLifecycleBuilder OnActivated(this IWindowsLifecycleBuilder lifecycle, WindowsLifecycle.OnActivated del) => lifecycle.OnEvent(del);
public static IWindowsLifecycleBuilder OnClosed(this IWindowsLifecycleBuilder lifecycle, WindowsLifecycle.OnClosed del) => lifecycle.OnEvent(del);
public static IWindowsLifecycleBuilder OnLaunching(this IWindowsLifecycleBuilder lifecycle, WindowsLifecycle.OnLaunching del) => lifecycle.OnEvent(del);
Expand Down
52 changes: 50 additions & 2 deletions src/Core/src/Platform/Windows/MauiWinUIApplication.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using System;
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.Hosting;
using Microsoft.Maui.LifecycleEvents;
using Microsoft.Windows.AppLifecycle;

namespace Microsoft.Maui
{
Expand All @@ -20,9 +21,17 @@ public abstract class MauiWinUIApplication : UI.Xaml.Application, IPlatformAppli

protected override void OnLaunched(UI.Xaml.LaunchActivatedEventArgs args)
{
// Windows running on a different thread will "launch" the app again
LaunchActivatedEventArgs = args;

var launchActivation = AppInstance.GetCurrent().GetActivatedEventArgs();

// A running WinUI app can be activated again without rebuilding the MAUI application.
// Reuse the existing services and let activation handlers short-circuit the relaunch path.
if (_application != null && _services != null)
{
if (launchActivation is AppActivationArguments activatedEventArgs && OnAppActivation(activatedEventArgs))
return;

_services.InvokeLifecycleEvents<WindowsLifecycle.OnLaunching>(del => del(this, args));
_services.InvokeLifecycleEvents<WindowsLifecycle.OnLaunched>(del => del(this, args));
return;
Expand All @@ -37,6 +46,14 @@ protected override void OnLaunched(UI.Xaml.LaunchActivatedEventArgs args)

_services = applicationContext.Services;

// Future AppInstance activation callbacks need the app-level services to exist first.
RegisterForAppActivation();

// Run the initial activation after services are available, but before OnLaunching/window creation,
// so handlers can redirect or suppress the default startup flow.
if (launchActivation is AppActivationArguments initialActivation && OnAppActivation(initialActivation))
return;

_services.InvokeLifecycleEvents<WindowsLifecycle.OnLaunching>(del => del(this, args));

_application = _services.GetRequiredService<IApplication>();
Expand All @@ -48,10 +65,41 @@ protected override void OnLaunched(UI.Xaml.LaunchActivatedEventArgs args)
_services.InvokeLifecycleEvents<WindowsLifecycle.OnLaunched>(del => del(this, args));
}

protected virtual bool OnAppActivation(AppActivationArguments args)
{
var wasHandled = false;

_services?.InvokeLifecycleEvents<WindowsLifecycle.OnAppActivation>(del =>
{
// Preserve any earlier "handled" result so multiple listeners can participate safely.
wasHandled = del(this, args) || wasHandled;
});

return wasHandled;
}

void RegisterForAppActivation()
{
if (_isRegisteredForAppActivation)
return;

_isRegisteredForAppActivation = true;

// After startup, later file/protocol/redirected activations are delivered through AppInstance.
AppInstance.GetCurrent().Activated += OnAppInstanceActivated;

void OnAppInstanceActivated(object? sender, AppActivationArguments args)
{
OnAppActivation(args);
}
Comment on lines +90 to +104
}

public static new MauiWinUIApplication Current => (MauiWinUIApplication)UI.Xaml.Application.Current;

public UI.Xaml.LaunchActivatedEventArgs LaunchActivatedEventArgs { get; protected set; } = null!;

bool _isRegisteredForAppActivation;

IServiceProvider? _services;

IApplication? _application;
Expand Down
6 changes: 5 additions & 1 deletion src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
#nullable enable
#nullable enable
Microsoft.Maui.LifecycleEvents.WindowsLifecycle.OnAppActivation
override Microsoft.Maui.Platform.MauiPasswordTextBox.OnCreateAutomationPeer() -> Microsoft.UI.Xaml.Automation.Peers.AutomationPeer!
static Microsoft.Maui.LifecycleEvents.WindowsLifecycleBuilderExtensions.OnAppActivation(this Microsoft.Maui.LifecycleEvents.IWindowsLifecycleBuilder! lifecycle, Microsoft.Maui.LifecycleEvents.WindowsLifecycle.OnAppActivation! del) -> Microsoft.Maui.LifecycleEvents.IWindowsLifecycleBuilder!
virtual Microsoft.Maui.LifecycleEvents.WindowsLifecycle.OnAppActivation.Invoke(Microsoft.UI.Xaml.Application! application, Microsoft.Windows.AppLifecycle.AppActivationArguments! args) -> bool
virtual Microsoft.Maui.MauiWinUIApplication.OnAppActivation(Microsoft.Windows.AppLifecycle.AppActivationArguments! args) -> bool
43 changes: 43 additions & 0 deletions src/Core/tests/UnitTests/LifecycleEvents/LifecycleEventsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,49 @@ public void CanAddMultipleEventsViaBuilder()
Assert.Equal(1, event2Fired);
}

#if WINDOWS
[Fact]
public void CanAddWindowsOnAppActivationLifecycleEvent()
{
var firstHandlerCalled = false;
var secondHandlerCalled = false;
var wasHandled = false;

var mauiApp = MauiApp.CreateBuilder()
.ConfigureLifecycleEvents(builder =>
{
builder.AddWindows(windows =>
{
windows.OnAppActivation((application, args) =>
{
firstHandlerCalled = true;
return false;
});

windows.OnAppActivation((application, args) =>
{
secondHandlerCalled = true;
return true;
});
});
})
.Build();

var service = mauiApp.Services.GetRequiredService<ILifecycleEventService>();

Assert.True(service.ContainsEvent(nameof(WindowsLifecycle.OnAppActivation)));

service.InvokeEvents<WindowsLifecycle.OnAppActivation>(nameof(WindowsLifecycle.OnAppActivation), del =>
{
wasHandled = del(null!, null!) || wasHandled;
});

Assert.True(firstHandlerCalled);
Assert.True(secondHandlerCalled);
Assert.True(wasHandled);
}
#endif

#if ANDROID
[Fact]
public void CanAddAndroidOnKeyDownLifecycleEvent()
Expand Down
Loading