Ejemplo n.º 1
0
    private static async void Retry(ResourceDictionary dic, bool isLocal)
    {
        try
        {
            if (!Dialog.Ask(LocalizationHelper.Get("S.SavingSettings.Title"), LocalizationHelper.Get("S.SavingSettings.Instruction"), LocalizationHelper.Get("S.SavingSettings.Message")))
            {
                return;
            }

            //Get a new instance, but elevated.
            var process = ProcessHelper.RestartAsAdminAdvanced("-settings");
            await Task.Delay(500);

            var settings = new XmlWriterSettings
            {
                Indent             = true,
                IndentChars        = "\t",
                OmitXmlDeclaration = true,
                CheckCharacters    = true,
                CloseOutput        = true,
                ConformanceLevel   = ConformanceLevel.Fragment,
                Encoding           = Encoding.UTF8
            };

            //Serialize the settings and pass to the new instance via IPC.
            await using var stream = new StringWriter();
            await using var writer = XmlWriter.Create(stream, settings);
            XamlWriter.Save(dic, writer);
            SettingsPersistenceChannel.SendMessage(process.Id, stream.ToString(), isLocal);

            //Since the other instance only exists to save the settings (no interface is displayed), the process must be stopped.
            process.Kill();
        }
        catch (Exception e)
        {
            LogWriter.Log(e, "Impossible to retry to save the settings.");
        }
    }
Ejemplo n.º 2
0
        private void App_Startup(object sender, StartupEventArgs e)
        {
            Global.StartupDateTime = DateTime.Now;

            //Unhandled Exceptions.
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.AssemblyResolve    += CurrentDomain_AssemblyResolve;

            //Increases the duration of the tooltip display.
            ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(int.MaxValue));

            var version = FrameworkHelper.GetFrameworkVersion();

            if (version > new Version(4, 7, 2))
            {
                SetSecurityProtocol();
            }

            //Parse arguments.
            Arguments.Prepare(e.Args);

            LocalizationHelper.SelectCulture(UserSettings.All.LanguageCode);
            ThemeHelper.SelectTheme(UserSettings.All.MainTheme);

            //Listen to changes in theme.
            SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;

            #region Download mode

            if (Arguments.IsInDownloadMode)
            {
                var downloader = new Downloader
                {
                    DownloadMode    = Arguments.DownloadMode,
                    DestinationPath = Arguments.DownloadPath
                };
                downloader.ShowDialog();

                Environment.Exit(90);
                return;
            }

            #endregion

            #region Settings persistence mode

            if (Arguments.IsInSettingsMode)
            {
                SettingsPersistenceChannel.RegisterServer();
                return;
            }

            #endregion

            #region If set, it allows only one instance per user

            //The singleton works on a per-user and per-executable mode.
            //Meaning that a different user and/or a different executable intances can co-exist.
            //Part of this code wont work on debug mode, since the SetForegroundWindow() needs focus on the foreground window calling the method.
            if (UserSettings.All.SingleInstance && !Arguments.NewInstance)
            {
                try
                {
                    using (var thisProcess = Process.GetCurrentProcess())
                    {
                        var user      = System.Security.Principal.WindowsIdentity.GetCurrent().User;
                        var name      = thisProcess.MainModule?.FileName ?? Assembly.GetEntryAssembly()?.Location ?? "ScreenToGif";
                        var location  = Convert.ToBase64String(Encoding.UTF8.GetBytes(name));
                        var mutexName = (user?.Value ?? Environment.UserName) + "_" + location;

                        _mutex = new Mutex(true, mutexName, out _accepted);

                        //If the mutext failed to be accepted, it means that another process already openned it.
                        if (!_accepted)
                        {
                            var warning = true;

                            //Switch to the other app (get only one, if multiple available). Use name of assembly.
                            using (var process = Process.GetProcessesByName(thisProcess.ProcessName).FirstOrDefault(f => f.MainWindowHandle != thisProcess.MainWindowHandle))
                            {
                                if (process != null)
                                {
                                    var handles = Util.Native.GetWindowHandlesFromProcess(process);

                                    //Show the window before setting focus.
                                    Util.Native.ShowWindow(handles.Count > 0 ? handles[0] : process.Handle, Util.Native.ShowWindowEnum.Show);

                                    //Set user the focus to the window.
                                    Util.Native.SetForegroundWindow(handles.Count > 0 ? handles[0] : process.Handle);
                                    warning = false;

                                    InstanceSwitcherChannel.SendMessage(e.Args);
                                }
                            }

                            //If no window available (app is in the system tray), display a warning.
                            if (warning)
                            {
                                Dialog.Ok(LocalizationHelper.Get("S.Warning.Single.Title"), LocalizationHelper.Get("S.Warning.Single.Header"), LocalizationHelper.Get("S.Warning.Single.Message"), Icons.Info);
                            }

                            Environment.Exit(0);
                            return;
                        }

                        //If this is the first instance, register the inter process channel to listen for other instances.
                        InstanceSwitcherChannel.RegisterServer();
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Impossible to check if another instance is running");
                }
            }

            #endregion

            //Render mode.
            RenderOptions.ProcessRenderMode = UserSettings.All.DisableHardwareAcceleration ? RenderMode.SoftwareOnly : RenderMode.Default;

            #region Net Framework

            if (version < new Version(4, 8))
            {
                var ask = Dialog.Ask(LocalizationHelper.Get("S.Warning.Net.Title"), LocalizationHelper.Get("S.Warning.Net.Header"), LocalizationHelper.Get("S.Warning.Net.Message"));

                if (ask)
                {
                    Process.Start("http://go.microsoft.com/fwlink/?LinkId=2085155");
                    return;
                }
            }

            #endregion

            if (version > new Version(4, 7))
            {
                SetWorkaroundForDispatcher();
            }

            #region Net Framework HotFixes

            //Only runs on Windows 7 SP1.
            if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        var search = new ManagementObjectSearcher("SELECT HotFixID FROM Win32_QuickFixEngineering WHERE HotFixID = 'KB4055002'").Get();
                        Global.IsHotFix4055002Installed = search.Count > 0;
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Log(ex, "Error while trying to know if a hot fix was installed.");
                    }
                });
            }

            #endregion

            #region Tray icon and view model

            NotifyIcon = (NotifyIcon)FindResource("NotifyIcon");

            if (NotifyIcon != null)
            {
                NotifyIcon.Visibility = UserSettings.All.ShowNotificationIcon || UserSettings.All.StartMinimized || UserSettings.All.StartUp == 5 ? Visibility.Visible : Visibility.Collapsed;

                //Replace the old option with the new setting.
                if (UserSettings.All.StartUp == 5)
                {
                    UserSettings.All.StartMinimized       = true;
                    UserSettings.All.ShowNotificationIcon = true;
                    UserSettings.All.StartUp = 0;
                }

                //using (var iconStream = GetResourceStream(new Uri("pack://application:,,,/Resources/Logo.ico"))?.Stream)
                //{
                //    if (iconStream != null)
                //        NotifyIcon.Icon = new System.Drawing.Icon(iconStream);
                //}
            }

            MainViewModel = (ApplicationViewModel)FindResource("AppViewModel") ?? new ApplicationViewModel();

            RegisterShortcuts();

            #endregion

            //var test = new TestField(); test.ShowDialog(); Environment.Exit(1); return;
            //var test = new Windows.EditorEx(); test.ShowDialog(); return;
            //var test = new Windows.NewWebcam(); test.ShowDialog(); return;
            //var test = Settings.UserSettings.All.StartupTop;

            #region Tasks

            Task.Factory.StartNew(MainViewModel.ClearTemporaryFiles, TaskCreationOptions.LongRunning);
            Task.Factory.StartNew(MainViewModel.CheckForUpdates, TaskCreationOptions.LongRunning);
            Task.Factory.StartNew(MainViewModel.SendFeedback, TaskCreationOptions.LongRunning);

            #endregion

            #region Startup

            if (Arguments.Open)
            {
                MainViewModel.Open.Execute(Arguments.WindownToOpen, true);
            }
            else
            {
                MainViewModel.Open.Execute(UserSettings.All.StartUp);
            }

            #endregion
        }