Skip to content

AppInstance.FindOrRegisterForKey("main").IsCurrent is always true #1832

@JohnCido

Description

@JohnCido

Describe the bug

I was trying to use the code in this repo to add single instance functionality to my app. But as described in the title. The AppInstance.FindOrRegisterForKey("main").IsCurrent is always true. So I can't use this to terminate the existing app instance at all.

Steps to reproduce the bug

  1. Create a new Solution using WinUI 3 single package template
  2. Replace part of codes in App.xaml.cs with the following:
protected override async void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
    // Get the activation args
    var appArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();

    // Get or register the main instance
    var mainInstance = Microsoft.Windows.AppLifecycle.AppInstance.FindOrRegisterForKey("main");

    // If the main instance isn't this current instance
    if (!mainInstance.IsCurrent)
    {
        // Redirect activation to that instance
        await mainInstance.RedirectActivationToAsync(appArgs);

        // And exit our instance and stop
        System.Diagnostics.Process.GetCurrentProcess().Kill();
        return;
    }

    // Otherwise, register for activation redirection
    Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().Activated += App_Activated;

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

private Window m_window;

private void App_Activated(object sender, Microsoft.Windows.AppLifecycle.AppActivationArguments e)
{

}
  1. Set a breakpoint at if (!mainInstance.IsCurrent) line.
  2. F5, then you will see IsCurrent with a true value
  3. Launch the app again using the Start Menu icon
  4. The IsCurrent value is still true

Expected behavior

It should not launch a second app instance just like the solution from this repo.

Screenshots

屏幕截图 2021-11-22 002311

NuGet package version

1.0.0

Packaging type

Packaged (MSIX)

Windows version

Windows 11 (22000)

IDE

Visual Studio 2022

Additional context

Tried both .NET 5 and 6, none of them are working. Should not be a Framework related issue.

Metadata

Metadata

Assignees

Labels

area-LifecycleTopics related to the AppLifecycle, providing lifecycle management for WindowsAppSDK apps

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions