Example #1
0
        private void Application_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));

            if (UserSettings.All.WorkaroundQuota)
            {
                BaseCompatibilityPreferences.HandleDispatcherRequestProcessingFailure = BaseCompatibilityPreferences.HandleDispatcherRequestProcessingFailureOptions.Reset;
            }

            #region Set network connection properties

            try
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to set the network properties");
            }

            #endregion

            //Parse arguments.
            if (e.Args.Length > 0)
            {
                Argument.Prepare(e.Args);
            }

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

            #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)
            {
                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 = Native.GetWindowHandlesFromProcess(process);

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

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

                            //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;
                        }
                    }
                }
                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 (!FrameworkHelper.HasFramework())
            {
                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

            #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 select = new SelectFolderDialog(); select.ShowDialog(); return;
            //var select = new TestField(); select.ShowDialog(); return;
            //var select = new Encoder(); select.ShowDialog(); return;
            //var select = new EditorEx(); select.ShowDialog(); return;

            #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

            //When starting minimized, the
            if (UserSettings.All.StartMinimized)
            {
                return;
            }

            if (UserSettings.All.StartUp == 4 || Argument.FileNames.Any())
            {
                MainViewModel.OpenEditor.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp < 1 || UserSettings.All.StartUp > 4)
            {
                MainViewModel.OpenLauncher.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp == 1)
            {
                MainViewModel.OpenRecorder.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp == 2)
            {
                MainViewModel.OpenWebcamRecorder.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp == 3)
            {
                MainViewModel.OpenBoardRecorder.Execute(null);
            }

            #endregion
        }