Ejemplo n.º 1
0
        private async void OpenFileUpdateUi(StorageFile file)
        {
            // Let's try to register this instance for this file.
            var instance = AppInstance.FindOrRegisterInstanceForKey(file.Name);

            if (instance.IsCurrentInstance)
            {
                Debug.WriteLine($"Registered {App.Id} for {file.Name}");
                // We successfully registered this instance.
                string text = await FileIO.ReadTextAsync(file);

                fileName.Text       = file.Name;
                fileText.Text       = text;
                closeFile.IsEnabled = true;
                openFile.IsEnabled  = false;
                isFileOpen          = true;
            }
            else
            {
                // Some other instance registered for this file, so we'll
                // warn the user and return.
                Debug.WriteLine($"Attempted to open {file.Name} more than once.");
                MessageDialog dialog = new MessageDialog(
                    "You already have this file open in another instance of BananaEdit.");
                await dialog.ShowAsync();
            }
        }
Ejemplo n.º 2
0
        // This project includes DISABLE_XAML_GENERATED_MAIN in the build properties,
        // which prevents the build system from generating the default Main method:
        // static void Main(string[] args)
        // {
        //     global::Windows.UI.Xaml.Application.Start((p) => new App());
        // }
        // TODO WTS: Update the logic in this method if you want to control the launching of multiple instances.
        // You may find the `AppInstance.GetActivatedEventArgs()` useful for your app-defined logic.
        public static void Main(string[] args)
        {
            // If the platform indicates a recommended instance, use that.
            if (AppInstance.RecommendedInstance != null)
            {
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
            else
            {
                // Update the logic below as appropriate for your app.
                // Multiple instances of an app are registered using keys.
                // Creating a unique key (as below) allows a new instance to always be created.
                // Always using the same key will mean there's only one ever one instance.
                // Or you can use your own logic to launch a new instance or switch to an existing one.
                var key      = Guid.NewGuid().ToString();
                var instance = AppInstance.FindOrRegisterInstanceForKey(key);

                if (instance.IsCurrentInstance)
                {
                    // If successfully registered this instance, do normal XAML initialization.
                    global::Windows.UI.Xaml.Application.Start((p) => new App());
                }
                else
                {
                    // Some other instance has registered for this key, redirect activation to that instance.
                    instance.RedirectActivationTo();
                }
            }
        }
Ejemplo n.º 3
0
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

            // If the Windows shell indicates a recommended instance, then
            // the app can choose to redirect this activation to that instance instead.
            if (AppInstance.RecommendedInstance != null)
            {
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
            else
            {
                // Define a key for this instance, based on some app-specific logic.
                // If the key is always unique, then the app will never redirect.
                // If the key is always non-unique, then the app will always redirect
                // to the first instance. In practice, the app should produce a key
                // that is sometimes unique and sometimes not, depending on its own needs.
                string key = Guid.NewGuid().ToString(); // always unique.
                                                        //string key = "Some-App-Defined-Key"; // never unique.
                var instance = AppInstance.FindOrRegisterInstanceForKey(key);
                if (instance.IsCurrentInstance)
                {
                    global::Xamarin.Forms.Forms.Init(e);
                    UserDialogs.Init();
                }
                else
                {
                    // Some other instance has registered for this key, so we'll
                    // redirect this activation to that instance instead.
                    instance.RedirectActivationTo();
                }
            }
            base.OnLaunched(e);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            // First, we'll get our activation event args, which are typically richer
            // than the incoming command-line args. We can use these in our app-defined
            // logic for generating the key for this instance.
            var activatedArgs = AppInstance.GetActivatedEventArgs();

            if (activatedArgs is CommandLineActivatedEventArgs commandLine && TryParseCommandLine(commandLine, out int id, out bool test))
            {
                _lastId = id;

                var instance = AppInstance.FindOrRegisterInstanceForKey(id.ToString());
                if (instance.IsCurrentInstance)
                {
                    // If we successfully registered this instance, we can now just
                    // go ahead and do normal XAML initialization.
                    global::Windows.UI.Xaml.Application.Start((p) => new App(id));
                }
                else
                {
                    // Some other instance has registered for this key, so we'll
                    // redirect this activation to that instance instead.
                    instance.RedirectActivationTo();
                }
            }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            if (ApiInformation.IsTypePresent("Windows.ApplicationModel.AppInstance"))
            {
                IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

                if (AppInstance.RecommendedInstance != null)
                {
                    AppInstance.RecommendedInstance.RedirectActivationTo();
                }
                else
                {
                    var instance = AppInstance.GetInstances().LastOrDefault();
                    if (instance == null || activatedArgs is Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
                    {
                        // If we successfully registered this instance, we can now just
                        // go ahead and do normal XAML initialization.
                        AppInstance.FindOrRegisterInstanceForKey(Guid.NewGuid().ToString());
                        global::Windows.UI.Xaml.Application.Start((p) => new App());
                    }
                    else
                    {
                        instance.RedirectActivationTo();
                    }
                }
            }
            else
            {
                global::Windows.UI.Xaml.Application.Start((p) => new App());
            }
        }
Ejemplo n.º 6
0
 private static void OpenNewInstance()
 {
     AppInstance.FindOrRegisterInstanceForKey(App.Id.ToString());
     App.IsFirstInstance = IsFirstInstance;
     Windows.UI.Xaml.Application.Start(p => new App());
     IsFirstInstance = false;
 }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            var activatedArgs = AppInstance.GetActivatedEventArgs();

            if (AppInstance.RecommendedInstance != null)
            {
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
            else
            {
                var key = Guid.NewGuid().ToString();
                if (activatedArgs is FileActivatedEventArgs fileActivatedEventArgs &&
                    fileActivatedEventArgs.Files.FirstOrDefault() is StorageFile file)
                {
                    key = Path.Combine(file.Path, file.Name);
                }

                var instance = AppInstance.FindOrRegisterInstanceForKey(key);
                if (instance.IsCurrentInstance)
                {
                    Application.Start(p => new App());
                }
                else
                {
                    instance.RedirectActivationTo();
                }
            }
        }
Ejemplo n.º 8
0
        private static async Task Main()
        {
            var args = Environment.GetCommandLineArgs();
            var proc = System.Diagnostics.Process.GetCurrentProcess();

            if (args.Length == 2)
            {
                var parsedCommands = CommandLineParser.ParseUntrustedCommands(args);

                if (parsedCommands != null && parsedCommands.Count > 0)
                {
                    foreach (var command in parsedCommands)
                    {
                        switch (command.Type)
                        {
                        case ParsedCommandType.ExplorerShellCommand:
                            await OpenShellCommandInExplorerAsync(command.Payload, proc.Id);

                            //Exit..

                            return;

                        default:
                            break;
                        }
                    }
                }
            }

            if (!ApplicationData.Current.RoamingSettings.Values.Get("AlwaysOpenANewInstance", false))
            {
                IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

                if (AppInstance.RecommendedInstance != null)
                {
                    AppInstance.RecommendedInstance.RedirectActivationTo();
                    return;
                }
                else if (activatedArgs is LaunchActivatedEventArgs)
                {
                    var launchArgs = activatedArgs as LaunchActivatedEventArgs;

                    var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1);
                    var instance  = AppInstance.FindOrRegisterInstanceForKey(activePid.ToString());
                    if (!instance.IsCurrentInstance && !string.IsNullOrEmpty(launchArgs.Arguments))
                    {
                        instance.RedirectActivationTo();
                        return;
                    }
                }
            }

            AppInstance.FindOrRegisterInstanceForKey(proc.Id.ToString());
            ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = proc.Id;
            Application.Start(_ => new App());
        }
Ejemplo n.º 9
0
        // This project includes DISABLE_XAML_GENERATED_MAIN in the build properties,
        // which prevents the build system from generating the default Main method:
        //static void Main(string[] args)
        //{
        //    global::Windows.UI.Xaml.Application.Start((p) => new App());
        //}

        // This example code shows how you could implement the required Main method to
        // support multi-instance redirection. The minimum requirement is to call
        // Application.Start with a new App object. Beyond that, you may delete the
        // rest of the example code and replace it with your custom code if you wish.

        static void Main(string[] args)
        {
            Debugger.Break();
            // First, we'll get our activation event args, which are typically richer
            // than the incoming command-line args. We can use these in our app-defined
            // logic for generating the key for this instance.
            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();
            var launchArgs  = activatedArgs as LaunchActivatedEventArgs;
            var arguments   = launchArgs?.Arguments;
            var commandArgs = activatedArgs as CommandLineActivatedEventArgs;

            arguments = arguments ?? commandArgs?.Operation.Arguments;
            if (arguments != null)
            {
                args = SplitArgs(arguments);
                if (arguments == commandArgs?.Operation.Arguments && args.Length >= 2)
                {
                    args = args.Skip(1).ToArray();
                }
            }
            // In some scenarios, the platform might indicate a recommended instance.
            // If so, we can redirect this activation to that instance instead, if we wish.
            if (AppInstance.RecommendedInstance != null)
            {
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
            else
            {
                // Define a key for this instance, based on some app-specific logic.
                // If the key is always unique, then the app will never redirect.
                // If the key is always non-unique, then the app will always redirect
                // to the first instance. In practice, the app should produce a key
                // that is sometimes unique and sometimes not, depending on its own needs.
                string key = "MainInstance";
                if (args.Length > 0)
                {
                    key = args[0];
                }
                //var instanceNo = GetInstanceNo();
                //string key = instanceNo.ToString();
                var instance = AppInstance.FindOrRegisterInstanceForKey(key);
                if (instance.IsCurrentInstance)
                {
                    // If we successfully registered this instance, we can now just
                    // go ahead and do normal XAML initialization.
                    global::Windows.UI.Xaml.Application.Start(p => new App());
                }
                else
                {
                    // Some other instance has registered for this key, so we'll
                    // redirect this activation to that instance instead.
                    instance.RedirectActivationTo();
                }
            }
        }
Ejemplo n.º 10
0
        // HACK - For debugging 2 instances on the same machine and 2 webcams
        private int HACK_GetVideoDeviceIndex()
        {
            var firstInstance = AppInstance.FindOrRegisterInstanceForKey("{44CD414E-B604-482E-8CFD-A9E09076CABD}");
            int idx           = 0;

            if (!firstInstance.IsCurrentInstance)
            {
                idx++;
            }
            return(idx);
        }
Ejemplo n.º 11
0
        // When the user is done editing the file, we should change our registration.
        private void CloseFile_Click(object sender, RoutedEventArgs e)
        {
            NoFileUpdateUi("[File closed]");

            // In the simple case, we can just unregister this instance so that
            // it no longer takes part in redirection.
            //AppInstance.Unregister();

            // For more complex behavior, we can re-register ourselves as available for re-use.
            // Multiple instances should be able to register as reusable, and each registration
            // must use a unique key, so we simply append the app's custom Id.
            AppInstance.FindOrRegisterInstanceForKey("REUSABLE" + App.Id.ToString());
        }
Ejemplo n.º 12
0
        private static void AssignOrCreateInstanceForFile(string filePath)
        {
            var instance = (GetLastActiveInstance() ?? AppInstance.FindOrRegisterInstanceForKey(App.Id.ToString()));

            if (instance.IsCurrentInstance)
            {
                App.IsFirstInstance = IsFirstInstance;
                Windows.UI.Xaml.Application.Start(p => new App());
                IsFirstInstance = false;
            }
            else
            {
                instance.RedirectActivationTo();
            }
        }
Ejemplo n.º 13
0
        private static void RedirectOrCreateNewInstance()
        {
            var instance = (GetLastActiveInstance() ?? AppInstance.FindOrRegisterInstanceForKey(App.Id.ToString()));

            if (instance.IsCurrentInstance)
            {
                Windows.UI.Xaml.Application.Start(p => new App());
            }
            else
            {
                // open new instance if user prefers to
                if (ApplicationSettingsStore.Read(SettingsKey.AlwaysOpenNewWindowBool) is bool alwaysOpenNewWindowBool && alwaysOpenNewWindowBool)
                {
                    OpenNewInstance();
                }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

            if (activatedArgs is ToastNotificationActivatedEventArgs)
            {
                return;
            }

            if (activatedArgs is CommandLineActivatedEventArgs CmdActivate)
            {
                if (CmdActivate.Operation.Arguments.StartsWith("RX-Explorer.exe"))
                {
                    if (AppInstance.RecommendedInstance != null)
                    {
                        AppInstance.RecommendedInstance.RedirectActivationTo();
                    }
                    else if (ApplicationData.Current.LocalSettings.Values["LastActiveGuid"] is string LastGuid &&
                             !string.IsNullOrWhiteSpace(LastGuid) &&
                             AppInstance.FindOrRegisterInstanceForKey(LastGuid) is AppInstance TargetInstance &&
                             !TargetInstance.IsCurrentInstance)
                    {
                        TargetInstance.RedirectActivationTo();
                    }
                    else if (AppInstance.GetInstances().FirstOrDefault() is AppInstance ExistInstance)
                    {
                        ExistInstance.RedirectActivationTo();
                    }
                    else
                    {
                        string      InstanceId = Guid.NewGuid().ToString();
                        AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                        ApplicationData.Current.LocalSettings.Values["LastActiveGuid"] = InstanceId;

                        Application.Start((p) => new App());
                    }
                }
                else
                {
                    string      InstanceId = Guid.NewGuid().ToString();
                    AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                    ApplicationData.Current.LocalSettings.Values["LastActiveGuid"] = InstanceId;

                    Application.Start((p) => new App());
                }
            }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

            if (activatedArgs is ToastNotificationActivatedEventArgs)
            {
                return;
            }

            AppInstance Instance = AppInstance.FindOrRegisterInstanceForKey(Guid.NewGuid().ToString());

            if (Instance.IsCurrentInstance)
            {
                Application.Start((p) => new App());
            }
            else
            {
                Instance.RedirectActivationTo();
            }
        }
Ejemplo n.º 16
0
        // This project includes DISABLE_XAML_GENERATED_MAIN in the build properties,
        // which prevents the build system from generating the default Main method:
        //static void Main(string[] args)
        //{
        //    global::Windows.UI.Xaml.Application.Start((p) => new App());
        //}

        // This example code shows how you could implement the required Main method to
        // support multi-instance redirection. The minimum requirement is to call
        // Application.Start with a new App object. Beyond that, you may delete the
        // rest of the example code and replace it with your custom code if you wish.
        static void Main(string[] args)
        {
            //global::Windows.UI.Xaml.Application.Start((p) => new App());


            //// In some scenarios, the platform might indicate a recommended instance.
            //// If so, we can redirect this activation to that instance instead, if we wish.
            if (AppInstance.RecommendedInstance != null)
            {
                // ???
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
            else
            {
                // Define a key for this instance, based on some app-specific logic.
                // If the key is always unique, then the app will never redirect.
                // If the key is always non-unique, then the app will always redirect
                // to the first instance. In practice, the app should produce a key
                // that is sometimes unique and sometimes not, depending on its own needs.
                uint   number   = CryptographicBuffer.GenerateRandomNumber();
                string key      = number.ToString();// (number % 2 == 0) ? "even" : "odd";
                var    instance = AppInstance.FindOrRegisterInstanceForKey(key);

                if (instance.IsCurrentInstance)
                {
                    // If we successfully registered this instance, we can now just
                    // go ahead and do normal XAML initialization.
                    //global::Windows.UI.Xaml.Application.Start((p) => new App());


                    global::Windows.UI.Xaml.Application.Start(delegate(Windows.UI.Xaml.ApplicationInitializationCallbackParams p) { var hoge = new App(); hoge.Instance = instance; });
                }
                else
                {
                    // Some other instance has registered for this key, so we'll
                    // redirect this activation to that instance instead.
                    instance.RedirectActivationTo();
                }
            }
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            var activatedArgs = AppInstance.GetActivatedEventArgs();

            if (AppInstance.RecommendedInstance != null)
            {
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
            else
            {
                var key      = Guid.NewGuid().ToString();
                var instance = AppInstance.FindOrRegisterInstanceForKey(key);
                if (instance.IsCurrentInstance)
                {
                    Windows.UI.Xaml.Application.Start(p => new App());
                }
                else
                {
                    instance.RedirectActivationTo();
                }
            }
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            bool        startNew = false;
            AppInstance current  = null;

            var familystring = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily.ToString();

            if (familystring.Contains("desktop", StringComparison.InvariantCultureIgnoreCase))
            {
                // Always start a new instance when invoked on desktop
                startNew = true;
            }
            else
            {
                // Only start a new instance on other OSes if none are running.
                var instances = AppInstance.GetInstances();
                if (instances.Count == 0)
                {
                    startNew = true;
                }
                else
                {
                    current = instances[0];
                }
            }

            if (startNew)
            {
                AppInstance.FindOrRegisterInstanceForKey("true");
#pragma warning disable CA1806 // Do not ignore method results
                global::Windows.UI.Xaml.Application.Start((p) => new App());
#pragma warning restore CA1806 // Do not ignore method results
            }
            else if (current != null)
            {
                current.RedirectActivationTo();
            }
        }
Ejemplo n.º 19
0
        // Default code-gen unless we include DISABLE_XAML_GENERATED_MAIN in the build properties.
        //static void Main(string[] args)
        //{
        //    global::Windows.UI.Xaml.Application.Start((p) => new App());
        //}

        #region Main
        static void Main(string[] args)
        {
            // First, get a list of all running instances of this app.
            instances = AppInstance.GetInstances();

            // Next, we'll get our rich activation event args.
            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

            // An app might want to set itself up for possible redirection in
            // the case where it opens files - for example, to prevent multiple
            // instances from working on the same file.
            if (activatedArgs is FileActivatedEventArgs fileArgs)
            {
                // For simplicity, we'll only look at the first file.
                IStorageItem file = fileArgs.Files.FirstOrDefault();
                if (file != null)
                {
                    // Let's try to register this instance for this file.
                    var instance = AppInstance.FindOrRegisterInstanceForKey(file.Name);
                    if (instance.IsCurrentInstance)
                    {
                        // If we successfully registered this instance, we can now just
                        // go ahead and do normal XAML initialization.
                        UpdateSharedInstanceNumber();
                        global::Windows.UI.Xaml.Application.Start((p) => new App());
                    }
                    else
                    {
                        // Some other instance registered for this file, so we'll
                        // redirect this activation to that instance instead.
                        instance.RedirectActivationTo();
                    }
                }
            }
            else
            {
                // The platform might provide a recommended instance.
                if (AppInstance.RecommendedInstance != null)
                {
                    AppInstance.RecommendedInstance.RedirectActivationTo();
                }
                else
                {
                    // If the platform hasn't expressed a preference, we need to examine all
                    // other instances to see if any are suitable for redirecting this request.
                    // In the simple case, any instance will do.
                    //AppInstance instance = instances.FirstOrDefault();

                    // If the app re-registers re-usable instances, we can filter for these instead.
                    AppInstance instance = instances.Where((i) => i.Key.StartsWith("REUSABLE")).FirstOrDefault();
                    if (instance != null)
                    {
                        Debug.WriteLine($"instance = {instance.Key}");
                        instance.RedirectActivationTo();
                    }
                    else
                    {
                        AppInstance.FindOrRegisterInstanceForKey("REUSABLE" + App.Id.ToString());
                        UpdateSharedInstanceNumber();
                        global::Windows.UI.Xaml.Application.Start((p) => new App());
                    }
                }
            }
        }
Ejemplo n.º 20
0
 public void CreateNewInstance()
 {
     Instance = AppInstance.FindOrRegisterInstanceForKey(ID.ToString());
     global::Windows.UI.Xaml.Application.Start((p) => new App());
 }
Ejemplo n.º 21
0
        public static void Main(string[] args)
        {
            // Check if this invocation already has a target instance (from the shell)
            if (AppInstance.RecommendedInstance is null)
            {
                string key = Guid.NewGuid().ToString("N");

                IActivatedEventArgs activatedEventArgs = AppInstance.GetActivatedEventArgs();

                // If the activation requests a file, check if it is already in use
                if (activatedEventArgs is FileActivatedEventArgs fileArgs &&
                    fileArgs.Files.FirstOrDefault() is StorageFile storageFile &&
                    TryGetInstanceForFilePath(storageFile.Path, out AppInstance? fileInstance))
                {
                    fileInstance !.RedirectActivationTo();

                    return;
                }

                // If the activation uses a protocol, handle the possible cases.
                // Currently there are two possible protocols being used:
                //   - [/switch?key=...] is used to request a direct switch to an existing instance.
                //     When this protocol is used, the target instance is always assumed to exist.
                //     In this case, we just retrieve the target instance by key and redirect.
                //   - [/file?path=...] is used to request a file activation from a timeline item.
                //     In this case we don't have a file instance, but only the target path.
                //     The activation is similar as the cases above: we first try to look for an
                //     existing instance working on that file, and in that case we just switch there.
                //     Otherwise we proceed with the usual registration, and the activation override
                //     will take care of trying to retrieve the target file, and open it if possible.
                if (activatedEventArgs is ProtocolActivatedEventArgs protocolArgs)
                {
                    // Direct switch requested to a target instance
                    if (protocolArgs.Uri.LocalPath.Equals("/switch"))
                    {
                        string targetKey = protocolArgs.Uri.Query.Substring("?key=".Length);

                        AppInstance.FindOrRegisterInstanceForKey(targetKey).RedirectActivationTo();

                        return;
                    }

                    // File request by path from a timeline item
                    if (protocolArgs.Uri.LocalPath.Equals("/file"))
                    {
                        string
                            escapedPath   = protocolArgs.Uri.Query.Substring("?path=".Length),
                            unescapedPath = Uri.UnescapeDataString(escapedPath);

                        // Activate the target instance as above, if one exists
                        if (TryGetInstanceForFilePath(unescapedPath, out AppInstance? pathInstance))
                        {
                            pathInstance !.RedirectActivationTo();

                            return;
                        }
                    }
                }

                // This will be a new app instance, which needs to be registered
                _ = AppInstance.FindOrRegisterInstanceForKey(key);

                // Start the app as usual, passing the current key
                Start(_ => new App(key));
            }
            else
            {
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Check if this application instance is the first one launched on the host device.
        /// </summary>
        /// <returns><c>true</c> if the current application instance is the first and therefore only instance.</returns>
        internal static bool IsFirstInstance()
        {
            var firstInstance = AppInstance.FindOrRegisterInstanceForKey("{44CD414E-B604-482E-8CFD-A9E09076CABD}");

            return(firstInstance.IsCurrentInstance);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

            if (AppInstance.GetInstances().Count == 0)
            {
                AppInstanceIdContainer.ClearAll();
            }

            switch (activatedArgs)
            {
            case ToastNotificationActivatedEventArgs ToastActivate:
            {
                switch (ToastActivate.Argument)
                {
                case "EnterBackgroundTips":
                {
                    if (AppInstance.RecommendedInstance != null)
                    {
                        AppInstance.RecommendedInstance.RedirectActivationTo();
                    }
                    else if (!string.IsNullOrWhiteSpace(AppInstanceIdContainer.LastActiveId))
                    {
                        do
                        {
                            if (AppInstance.GetInstances().Any((Ins) => Ins.Key == AppInstanceIdContainer.LastActiveId))
                            {
                                if (AppInstance.FindOrRegisterInstanceForKey(AppInstanceIdContainer.LastActiveId) is AppInstance TargetInstance)
                                {
                                    TargetInstance.RedirectActivationTo();
                                }

                                break;
                            }
                            else
                            {
                                AppInstanceIdContainer.UngisterId(AppInstanceIdContainer.LastActiveId);
                            }
                        }while (!string.IsNullOrEmpty(AppInstanceIdContainer.LastActiveId));
                    }

                    break;
                }

                case "Restart":
                {
                    string      InstanceId = Guid.NewGuid().ToString();
                    AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                    AppInstanceIdContainer.RegisterId(InstanceId);

                    Application.Start((p) => new App());
                    break;
                }
                }

                break;
            }

            case CommandLineActivatedEventArgs CmdActivate:
            {
                if (CmdActivate.Operation.Arguments.StartsWith("RX-Explorer.exe", StringComparison.OrdinalIgnoreCase))
                {
                    if (AppInstance.RecommendedInstance != null)
                    {
                        AppInstance.RecommendedInstance.RedirectActivationTo();
                    }
                    else if (!string.IsNullOrWhiteSpace(AppInstanceIdContainer.LastActiveId))
                    {
                        do
                        {
                            if (AppInstance.GetInstances().Any((Ins) => Ins.Key == AppInstanceIdContainer.LastActiveId))
                            {
                                if (AppInstance.FindOrRegisterInstanceForKey(AppInstanceIdContainer.LastActiveId) is AppInstance TargetInstance)
                                {
                                    TargetInstance.RedirectActivationTo();
                                }

                                break;
                            }
                            else
                            {
                                AppInstanceIdContainer.UngisterId(AppInstanceIdContainer.LastActiveId);
                            }
                        }while (!string.IsNullOrEmpty(AppInstanceIdContainer.LastActiveId));
                    }
                    else
                    {
                        string      InstanceId = Guid.NewGuid().ToString();
                        AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                        AppInstanceIdContainer.RegisterId(InstanceId);

                        Application.Start((p) => new App());
                    }
                }
                else
                {
                    if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("AlwaysStartNew"))
                    {
                        ApplicationData.Current.LocalSettings.Values["AlwaysStartNew"] = true;
                    }

                    bool AlwaysStartNew = Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["AlwaysStartNew"]);

                    if (AlwaysStartNew)
                    {
                        string      InstanceId = Guid.NewGuid().ToString();
                        AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                        AppInstanceIdContainer.RegisterId(InstanceId);

                        Application.Start((p) => new App());
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(AppInstanceIdContainer.LastActiveId))
                        {
                            do
                            {
                                if (AppInstance.GetInstances().Any((Ins) => Ins.Key == AppInstanceIdContainer.LastActiveId))
                                {
                                    if (AppInstance.FindOrRegisterInstanceForKey(AppInstanceIdContainer.LastActiveId) is AppInstance TargetInstance)
                                    {
                                        TargetInstance.RedirectActivationTo();
                                    }

                                    break;
                                }
                                else
                                {
                                    AppInstanceIdContainer.UngisterId(AppInstanceIdContainer.LastActiveId);
                                }
                            }while (!string.IsNullOrEmpty(AppInstanceIdContainer.LastActiveId));
                        }
                        else
                        {
                            string      InstanceId = Guid.NewGuid().ToString();
                            AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                            AppInstanceIdContainer.RegisterId(InstanceId);

                            Application.Start((p) => new App());
                        }
                    }
                }

                break;
            }

            case LaunchActivatedEventArgs LaunchArg:
            {
                if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("AlwaysStartNew"))
                {
                    ApplicationData.Current.LocalSettings.Values["AlwaysStartNew"] = true;
                }

                bool AlwaysStartNew = Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["AlwaysStartNew"]);

                if (AlwaysStartNew)
                {
                    string      InstanceId = Guid.NewGuid().ToString();
                    AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                    AppInstanceIdContainer.RegisterId(InstanceId);

                    Application.Start((p) => new App());
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(AppInstanceIdContainer.LastActiveId))
                    {
                        do
                        {
                            if (AppInstance.GetInstances().Any((Ins) => Ins.Key == AppInstanceIdContainer.LastActiveId))
                            {
                                if (AppInstance.FindOrRegisterInstanceForKey(AppInstanceIdContainer.LastActiveId) is AppInstance TargetInstance)
                                {
                                    TargetInstance.RedirectActivationTo();
                                }

                                break;
                            }
                            else
                            {
                                AppInstanceIdContainer.UngisterId(AppInstanceIdContainer.LastActiveId);
                            }
                        }while (!string.IsNullOrEmpty(AppInstanceIdContainer.LastActiveId));
                    }
                    else
                    {
                        string      InstanceId = Guid.NewGuid().ToString();
                        AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                        AppInstanceIdContainer.RegisterId(InstanceId);

                        Application.Start((p) => new App());
                    }
                }

                break;
            }

            case FileActivatedEventArgs _:
            {
                if (!string.IsNullOrWhiteSpace(AppInstanceIdContainer.LastActiveId))
                {
                    do
                    {
                        if (AppInstance.GetInstances().Any((Ins) => Ins.Key == AppInstanceIdContainer.LastActiveId))
                        {
                            if (AppInstance.FindOrRegisterInstanceForKey(AppInstanceIdContainer.LastActiveId) is AppInstance TargetInstance)
                            {
                                TargetInstance.RedirectActivationTo();
                            }

                            break;
                        }
                        else
                        {
                            AppInstanceIdContainer.UngisterId(AppInstanceIdContainer.LastActiveId);
                        }
                    }while (!string.IsNullOrEmpty(AppInstanceIdContainer.LastActiveId));
                }
                else
                {
                    string      InstanceId = Guid.NewGuid().ToString();
                    AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                    AppInstanceIdContainer.RegisterId(InstanceId);

                    Application.Start((p) => new App());
                }

                break;
            }

            default:
            {
                string      InstanceId = Guid.NewGuid().ToString();
                AppInstance Instance   = AppInstance.FindOrRegisterInstanceForKey(InstanceId);
                AppInstanceIdContainer.RegisterId(InstanceId);

                Application.Start((p) => new App());
                break;
            }
            }
        }
Ejemplo n.º 24
0
        private static async Task Main()
        {
            var proc = System.Diagnostics.Process.GetCurrentProcess();

            if (!ApplicationData.Current.LocalSettings.Values.Get("AlwaysOpenANewInstance", false))
            {
                IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

                if (AppInstance.RecommendedInstance != null)
                {
                    AppInstance.RecommendedInstance.RedirectActivationTo();
                    await TerminateUwpAppInstance(proc.Id);

                    return;
                }
                else if (activatedArgs is LaunchActivatedEventArgs)
                {
                    var launchArgs = activatedArgs as LaunchActivatedEventArgs;

                    if (launchArgs.PrelaunchActivated && AppInstance.GetInstances().Count == 0)
                    {
                        AppInstance.FindOrRegisterInstanceForKey(PrelaunchInstanceKey);
                        ApplicationData.Current.LocalSettings.Values["WAS_PRELAUNCH_INSTANCE_ACTIVATED"] = false;
                        Application.Start(_ => new App());
                        return;
                    }
                    else
                    {
                        bool wasPrelaunchInstanceActivated = ApplicationData.Current.LocalSettings.Values.Get("WAS_PRELAUNCH_INSTANCE_ACTIVATED", true);
                        if (AppInstance.GetInstances().Any(x => x.Key.Equals(PrelaunchInstanceKey)) && !wasPrelaunchInstanceActivated)
                        {
                            var plInstance = AppInstance.GetInstances().First(x => x.Key.Equals(PrelaunchInstanceKey));
                            ApplicationData.Current.LocalSettings.Values["WAS_PRELAUNCH_INSTANCE_ACTIVATED"] = true;
                            plInstance.RedirectActivationTo();
                            await TerminateUwpAppInstance(proc.Id);

                            return;
                        }
                        else
                        {
                            var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1);
                            var instance  = AppInstance.FindOrRegisterInstanceForKey(activePid.ToString());
                            if (!instance.IsCurrentInstance && !string.IsNullOrWhiteSpace(launchArgs.Arguments))
                            {
                                instance.RedirectActivationTo();
                                await TerminateUwpAppInstance(proc.Id);

                                return;
                            }
                        }
                    }
                }
                else if (activatedArgs is CommandLineActivatedEventArgs cmdLineArgs)
                {
                    var operation      = cmdLineArgs.Operation;
                    var cmdLineString  = operation.Arguments;
                    var parsedCommands = CommandLineParser.ParseUntrustedCommands(cmdLineString);

                    if (parsedCommands != null)
                    {
                        foreach (var command in parsedCommands)
                        {
                            switch (command.Type)
                            {
                            case ParsedCommandType.ExplorerShellCommand:
                                if (!CommonPaths.ShellPlaces.ContainsKey(command.Payload.ToUpperInvariant()))
                                {
                                    await OpenShellCommandInExplorerAsync(command.Payload, proc.Id);

                                    return;     // Exit
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }

                    // Always open a new instance for OpenDialog
                    if (parsedCommands == null || !parsedCommands.Any(x => x.Type == ParsedCommandType.OutputPath))
                    {
                        var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1);
                        var instance  = AppInstance.FindOrRegisterInstanceForKey(activePid.ToString());
                        if (!instance.IsCurrentInstance)
                        {
                            instance.RedirectActivationTo();
                            await TerminateUwpAppInstance(proc.Id);

                            return;
                        }
                    }
                }
                else if (activatedArgs is FileActivatedEventArgs)
                {
                    var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1);
                    var instance  = AppInstance.FindOrRegisterInstanceForKey(activePid.ToString());
                    if (!instance.IsCurrentInstance)
                    {
                        instance.RedirectActivationTo();
                        await TerminateUwpAppInstance(proc.Id);

                        return;
                    }
                }
            }

            AppInstance.FindOrRegisterInstanceForKey(proc.Id.ToString());
            ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = proc.Id;
            Application.Start(_ => new App());
        }