How do I determine if a page opened at app startup or during the middle of the app?

131 Views Asked by At

I'm writing a .NET Maui app and I have a content page where hen it opens at the start of the program and the user clicks the Cancel button I want the entire application to close.

However, if the same page is opened at some point within the program and the user clicks the Cancel button, I would like only the current content page to close and the application to continue.

To me, this sounds like an if-else command on the Cancel button.

I do have all the content pages I want to access in a folder called Pages.

My real question is:

Is there a way to determine if a content page was opened from application start up?

2

There are 2 best solutions below

1
Guangyu Bai - MSFT On

You can check the App lifecycle of the Maui. Apps generally have four execution states: not running, running, deactivated, and stopped.

How do I determine if a page opened at app startup or during the middle of the app?

Usually, you can overwrite the Created method to detect if the app is started for the first time. When the app is started, the Created and Activated events are raised and the app is running.

If the user returns to the running app, the Resuming event is raised and app is running.

0
Isidoros Moulas On

There are 2 solutions.

The 1st solution is to accomplish that by using flags.

At a new file eg Globals.cs you will have the following

public class Globals
{
   public static bool isFirstTime = true;
}

And at your AppShell.xaml.cs

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();

        RegisterRoutes();
        BindingContext = this;

        Navigation.PushAsync(new MyPage());
   }
}

Then at your MyPage you will check the Globals.isFirstTime variable and proceed accordingly.

The 2nd solution is to check the navigation stack.

var navigation = Shell.Current.Navigation;
var pages = navigation.NavigationStack;
for (var i = pages.Count - 1; i >= 1; i--)
{
   //navigation.RemovePage(pages[i]);
}

The above code (just an example), removes all the pages from the navigation stack. At the beginning of the stack are the pages as they opened, while at the end is the last opened page.

So, you can check the position of your MyPage and proceed with your code.

hope that helps!