/// <summary>
        ///     Check if Ghostscript is installed with a given version. It does a lookup in the registry and checks if the paths
        ///     exist.
        /// </summary>
        /// <param name="version">Name of the version to check, i.e. "9.05"</param>
        /// <returns>A GhostscriptVersion object if a version has been found, null otherwise</returns>
        private GhostscriptVersion IsGhostscriptInstalled(string version)
        {
            try
            {
                IRegistryKey myKey = _registry.LocalMachine.OpenSubKey(RegistryPath + "\\" + version);
                if (myKey == null)
                {
                    return(null);
                }

                var gsDll = (string)myKey.GetValue("GS_DLL");
                var gsLib = (string)myKey.GetValue("GS_LIB");

                var gsExe = _pathSafe.Combine(_pathSafe.GetDirectoryName(gsDll), "gswin32c.exe");

                myKey.Close();
                if (_file.Exists(gsExe))
                {
                    return(new GhostscriptVersion(version, gsExe, gsLib));
                }
            }
            catch
            {
                return(null);
            }

            return(null);
        }
Example #2
0
        private static string TryFindInstallationPath(string msiDisplayName, string applicationExeName, IRegistry registry, IFile file)
        {
            foreach (string key in SoftwareKeys)
            {
                using (IRegistryKey rk = registry.LocalMachine.OpenSubKey(key))
                {
                    if (rk == null)
                    {
                        continue;
                    }

                    //Let's go through the registry keys and get the info we need:
                    foreach (string skName in rk.GetSubKeyNames())
                    {
                        using (IRegistryKey sk = rk.OpenSubKey(skName))
                        {
                            if (sk == null)
                            {
                                continue;
                            }

                            try
                            {
                                //first look for PDF Architect 3
                                //If the key has value, continue, if not, skip it:
                                string displayName = sk.GetValue("DisplayName").ToString();
                                if ((displayName.StartsWith(msiDisplayName, StringComparison.OrdinalIgnoreCase)) &&
                                    !displayName.Contains("Enterprise") &&
                                    (sk.GetValue("Publisher").ToString().Contains("pdfforge")) &&
                                    (sk.GetValue("InstallLocation") != null))
                                {
                                    var installLocation = sk.GetValue("InstallLocation").ToString();
                                    var exePath         = Path.Combine(installLocation, applicationExeName);

                                    if (file.Exists(exePath))
                                    {
                                        return(exePath);
                                    }

                                    // if the exe does not exist, this is the wrong path
                                    return(null);
                                }
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }
                    }
                }
            }
            return(null);
        }
Example #3
0
        public void LoadRegTest()
        {
            var oMareRegHandler = new MareRegHandler(RegFake, MsgBoxFake);

            oMareRegHandler.LoadReg();

            A.CallTo(() => RegFake.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}")).MustHaveHappened();
            A.CallTo(() => RegKeyFake.GetValue("KMD_EnableInternalLargePage", null)).MustHaveHappened();
            A.CallTo(() => RegKeyFake.GetValue("EnableCrossFireAutoLink", null)).MustHaveHappened();
            A.CallTo(() => RegKeyFake.GetValue("EnableUlps", null)).MustHaveHappened();
            A.CallTo(() => RegKeyFake.GetValue("DriverDesc", null)).MustHaveHappened();
            Assert.Collection(oMareRegHandler.AllGFX, x => new GFX(0, 0, 0, 0, "FAKE_GPU"));
        }
Example #4
0
        /// <summary>
        /// Gets the phone format from registry.
        /// </summary>
        /// <param name="countryCode">The country code.</param>
        /// <param name="distanceRule">The distance rule.</param>
        /// <returns>The string representation of the country's selected phone number format or <value>String.Empty</value>, if an error occured.</returns>
        public string GetPhoneFormat(int countryCode, DISTANCE_RULE distanceRule)
        {
            if (distanceRule == DISTANCE_RULE.CANONICAL)
            {
                return(PhoneNumberConstants.CANONICAL_FORMAT);
            }

            IRegistryKey hklmCountry = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_COUNTRYLIST_LEGACY);

            if (hklmCountry == null)
            {
                hklmCountry = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_COUNTRYLIST_MODERN);
            }

            try
            {
                hklmCountry = hklmCountry.OpenSubKey(countryCode.ToString());
                object curFormat = hklmCountry.GetValue(distanceRule.ToString());
                if (curFormat != null)
                {
                    return(curFormat.ToString());
                }
            }
            catch { }

            return(String.Empty);
        }
Example #5
0
        public MareRegHandlerTests()
        {
            RegKeyFake = A.Fake <IRegistryKey>();
            A.CallTo(() => RegKeyFake.GetSubKeyNames()).Returns(new string[] { "1" });
            A.CallTo(() => RegKeyFake.GetValue("KMD_EnableInternalLargePage", null)).Returns(0);
            A.CallTo(() => RegKeyFake.GetValue("EnableCrossFireAutoLink", null)).Returns(0);
            A.CallTo(() => RegKeyFake.GetValue("EnableUlps", null)).Returns(0);
            A.CallTo(() => RegKeyFake.GetValue("DriverDesc", null)).Returns("FAKE_GPU");
            A.CallTo(() => RegKeyFake.SetValue(A <string> .Ignored, A <object> .Ignored, A <RegistryValueKind> .Ignored)).DoesNothing();
            A.CallTo(() => RegKeyFake.OpenSubKey(A <string> .Ignored, A <bool> .Ignored)).Returns(RegKeyFake);

            RegFake = A.Fake <IRegistry>();
            A.CallTo(() => RegFake.OpenSubKey(A <string> .Ignored)).Returns(RegKeyFake);

            MsgBoxFake = A.Fake <IMessageBox>();
            A.CallTo(() => MsgBoxFake.Show(A <string> .Ignored)).DoesNothing();
        }
Example #6
0
        /// <summary>
        /// Gets the value or empty.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="valueName">Name of the value.</param>
        /// <returns></returns>
        private static string GetValueOrEmpty(IRegistryKey key, string valueName)
        {
            object value = key.GetValue(valueName);

            if (value == null)
            {
                return(string.Empty);
            }
            return(value.ToString());
        }
Example #7
0
        private string GetRegistryRepositoryPath(XElement packagesElement, IEnumerable <IRegistryKey> registryKeys)
        {
            string keyName = packagesElement.GetOptionalAttributeValue("keyName");

            if (String.IsNullOrEmpty(keyName))
            {
                ShowErrorMessage(VsResources.TemplateWizard_MissingRegistryKeyName);
                throw new WizardBackoutException();
            }

            IRegistryKey repositoryKey   = null;
            string       repositoryValue = null;

            // When pulling the repository from the registry, use CurrentUser first, falling back onto LocalMachine
            registryKeys = registryKeys ??
                           new[] {
                new RegistryKeyWrapper(Microsoft.Win32.Registry.CurrentUser),
                new RegistryKeyWrapper(Microsoft.Win32.Registry.LocalMachine)
            };

            // Find the first registry key that supplies the necessary subkey/value
            foreach (var registryKey in registryKeys)
            {
                repositoryKey = registryKey.OpenSubKey(RegistryKeyRoot);

                if (repositoryKey != null)
                {
                    repositoryValue = repositoryKey.GetValue(keyName) as string;

                    if (!String.IsNullOrEmpty(repositoryValue))
                    {
                        break;
                    }

                    repositoryKey.Close();
                }
            }

            if (repositoryKey == null)
            {
                ShowErrorMessage(String.Format(VsResources.TemplateWizard_RegistryKeyError, RegistryKeyRoot));
                throw new WizardBackoutException();
            }

            if (String.IsNullOrEmpty(repositoryValue))
            {
                ShowErrorMessage(String.Format(VsResources.TemplateWizard_InvalidRegistryValue, keyName, RegistryKeyRoot));
                throw new WizardBackoutException();
            }

            // Ensure a trailing slash so that the path always gets read as a directory
            repositoryValue = PathUtility.EnsureTrailingSlash(repositoryValue);

            return(Path.GetDirectoryName(repositoryValue));
        }
        /// <summary>
        /// Gets the folder location where packages have been laid down in a registry-specified location.
        /// </summary>
        /// <param name="keyName">The registry key name that specifies the packages location.</param>
        /// <returns>The absolute path to the packages folder specified in the registry.</returns>
        private string GetRegistryRepositoryPath(string keyName)
        {
            IRegistryKey repositoryKey   = null;
            string       repositoryValue = null;

            // When pulling the repository from the registry, use CurrentUser first, falling back onto LocalMachine
            // Documented here: https://docs.microsoft.com/nuget/visual-studio-extensibility/visual-studio-templates#registry-specified-folder-path
            var registryKeys = new[]
            {
                new RegistryKeyWrapper(RegistryHive.CurrentUser),
                new RegistryKeyWrapper(RegistryHive.LocalMachine, RegistryView.Registry32)
            };

            // Find the first registry key that supplies the necessary subkey/value
            foreach (var registryKey in registryKeys)
            {
                repositoryKey = registryKey.OpenSubKey(_registryKeyRoot);

                if (repositoryKey != null)
                {
                    repositoryValue = repositoryKey.GetValue(keyName) as string;

                    if (!string.IsNullOrEmpty(repositoryValue))
                    {
                        break;
                    }

                    repositoryKey.Close();
                }
            }

            if (repositoryKey == null)
            {
                var errorMessage = string.Format(VsResources.PreinstalledPackages_RegistryKeyError, _registryKeyRoot);
                _errorHandler(errorMessage);

                // The error is fatal, cannot continue
                throw new InvalidOperationException(errorMessage);
            }

            if (string.IsNullOrEmpty(repositoryValue))
            {
                var errorMessage = string.Format(VsResources.PreinstalledPackages_InvalidRegistryValue, keyName, _registryKeyRoot);
                _errorHandler(errorMessage);

                // The error is fatal, cannot continue
                throw new InvalidOperationException(errorMessage);
            }

            // Ensure a trailing slash so that the path always gets read as a directory
            repositoryValue = PathUtility.EnsureTrailingSlash(repositoryValue);

            return(Path.GetDirectoryName(repositoryValue));
        }
Example #9
0
        public void ExtensionUninstalledNoLogFile()
        {
            DataStore store = new DataStore(_registry, _logFile);

            store.MarkUninstalled(_entry);
            store.Save();

            Assert.AreEqual(1, store.Log.Count);
            Assert.AreEqual(_entry.Id, store.Log[0].Id);
            Assert.AreEqual("Uninstalled", store.Log[0].Action);
            Assert.AreEqual(_entry.Id, _registry.GetValue("disable"));
        }
Example #10
0
        /// <summary>
        /// Gets the folder location where packages have been laid down in a registry-specified location.
        /// </summary>
        /// <param name="keyName">The registry key name that specifies the packages location.</param>
        /// <param name="registryKeys">The optional list of parent registry keys to look in (used for unit tests).</param>
        /// <param name="throwingErrorHandler">
        /// An error handler that accepts the error message string and then throws
        /// the appropriate exception.
        /// </param>
        /// <returns>The absolute path to the packages folder specified in the registry.</returns>
        internal string GetRegistryRepositoryPath(string keyName, IEnumerable <IRegistryKey> registryKeys, Action <string> throwingErrorHandler)
        {
            IRegistryKey repositoryKey   = null;
            string       repositoryValue = null;

            // When pulling the repository from the registry, use CurrentUser first, falling back onto LocalMachine
            registryKeys = registryKeys ??
                           new[]
            {
                new RegistryKeyWrapper(Registry.CurrentUser),
                new RegistryKeyWrapper(Registry.LocalMachine)
            };

            // Find the first registry key that supplies the necessary subkey/value
            foreach (var registryKey in registryKeys)
            {
                repositoryKey = registryKey.OpenSubKey(RegistryKeyRoot);

                if (repositoryKey != null)
                {
                    repositoryValue = repositoryKey.GetValue(keyName) as string;

                    if (!String.IsNullOrEmpty(repositoryValue))
                    {
                        break;
                    }

                    repositoryKey.Close();
                }
            }

            if (repositoryKey == null)
            {
                throwingErrorHandler(String.Format(VsResources.PreinstalledPackages_RegistryKeyError, RegistryKeyRoot));
                Debug.Fail("throwingErrorHandler did not throw");
            }

            if (String.IsNullOrEmpty(repositoryValue))
            {
                throwingErrorHandler(String.Format(VsResources.PreinstalledPackages_InvalidRegistryValue, keyName, RegistryKeyRoot));
                Debug.Fail("throwingErrorHandler did not throw");
            }

            // Ensure a trailing slash so that the path always gets read as a directory
            repositoryValue = PathUtility.EnsureTrailingSlash(repositoryValue);

            return(Path.GetDirectoryName(repositoryValue));
        }
Example #11
0
        private bool TryFindInRegistry(string exeName, out string fullPath)
        {
            fullPath = null;

            const string keyBase     = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
            string       expectedKey = string.Format(@"{0}\{1}", keyBase, exeName);

            IRegistryKey hklm    = _registry.LocalMachine;
            IRegistryKey fileKey = hklm.OpenSubKey(expectedKey);

            if (fileKey == null)
            {
                return(false);
            }

            object result;

            try
            {
                result = fileKey.GetValue(string.Empty);
            }
            finally
            {
                fileKey.Close();
            }

            if (result == null)
            {
                return(false);
            }

            string suggestedPath = result.ToString();
            bool   exists        = _fileSystem.File.Exists(suggestedPath);

            if (!exists)
            {
                _log.Debug(
                    "{0} was specified in registry to be located at {1}, but it wasn't found there.",
                    exeName,
                    suggestedPath);
                return(false);
            }

            _log.Debug("Found {0} at {1} (via registry).", exeName, suggestedPath);
            fullPath = suggestedPath;
            return(true);
        }
Example #12
0
        private string GetRInstallPathFromRCoreKegKey(IRegistryKey rCoreKey, StringBuilder logger)
        {
            string installPath = null;

            string[] subKeyNames = rCoreKey.GetSubKeyNames();
            string[] valueNames  = rCoreKey.GetValueNames();
            if (valueNames.Length == 0)
            {
                doLogSetEnvVarWarn("Did not find any value names under " + rCoreKey, logger);
                return(RecurseFirstSubkey(rCoreKey, logger));
            }
            else
            {
                const string installPathKey = "InstallPath";
                if (valueNames.Contains(installPathKey))
                {
                    doLogSetEnvVarInfo("Found sub-key InstallPath under " + rCoreKey, logger);
                    installPath = (string)rCoreKey.GetValue(installPathKey);
                }
                else
                {
                    doLogSetEnvVarInfo("Did not find sub-key InstallPath under " + rCoreKey, logger);
                    if (valueNames.Contains("Current Version"))
                    {
                        doLogSetEnvVarInfo("Found sub-key Current Version under " + rCoreKey, logger);
                        string currentVersion = GetRCurrentVersionStringFromRegistry(rCoreKey);
                        if (subKeyNames.Contains(currentVersion))
                        {
                            IRegistryKey rVersionCoreKey = rCoreKey.OpenSubKey(currentVersion);
                            return(GetRInstallPathFromRCoreKegKey(rVersionCoreKey, logger));
                        }
                        else
                        {
                            doLogSetEnvVarWarn("Sub key " + currentVersion + " not found in " + rCoreKey, logger);
                        }
                    }
                    else
                    {
                        doLogSetEnvVarInfo("Did not find sub-key Current Version under " + rCoreKey, logger);
                        return(RecurseFirstSubkey(rCoreKey, logger));
                    }
                }
            }
            doLogSetEnvVarInfo(string.Format("InstallPath value of key " + rCoreKey.ToString() + ": {0}",
                                             installPath == null ? "null" : installPath), logger);
            return(installPath);
        }
Example #13
0
        private void RecurseCopyKey(IRegistryKey sourceKey, IRegistryKey destinationKey)
        {
            //copy all the values
            foreach (var valueName in sourceKey.GetValueNames())
            {
                var objValue = sourceKey.GetValue(valueName);
                var valKind  = sourceKey.GetValueKind(valueName);
                destinationKey.SetValue(valueName, objValue, valKind);
            }

            //For Each subKey
            //Create a new subKey in destinationKey
            //Call myself
            foreach (var sourceSubKeyName in sourceKey.GetSubKeyNames())
            {
                var sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName);
                var destSubKey   = destinationKey.CreateSubKey(sourceSubKeyName);
                RecurseCopyKey(sourceSubKey, destSubKey);
            }
        }
Example #14
0
        // Token: 0x0600032F RID: 815 RVA: 0x000122A8 File Offset: 0x000104A8
        private static string GetFromRegistry()
        {
            Exception    ex;
            IRegistryKey registryKey = Dependencies.RegistryKeyProvider.TryOpenKey(SharedHelper.AmRegKeyRoot, ref ex);

            if (ex != null)
            {
                throw ex;
            }
            string result = string.Empty;

            if (registryKey != null)
            {
                using (registryKey)
                {
                    result = (string)registryKey.GetValue("LastKnownGoodConfig", string.Empty);
                }
            }
            return(result);
        }
Example #15
0
        // Token: 0x06000818 RID: 2072 RVA: 0x00027444 File Offset: 0x00025644
        private bool ReadProperty <T>(string keyName, string propertyName, out T foundValue, T defaultValue)
        {
            bool result = false;

            foundValue = defaultValue;
            Exception ex = null;

            using (IRegistryKey registryKey = SharedDependencies.RegistryKeyProvider.TryOpenKey(keyName, ref ex))
            {
                if (registryKey != null)
                {
                    object value = registryKey.GetValue(propertyName, defaultValue);
                    if (value != null)
                    {
                        result     = true;
                        foundValue = (T)((object)value);
                    }
                }
            }
            return(result);
        }
Example #16
0
        /// <summary>
        /// Gets the user's area code from the Registry.
        /// </summary>
        /// <returns>A string containing the user's area code or <value>String.Empty</value>, if an error occured.</returns>
        public string GetUserAreaCode()
        {
            IRegistryKey hklmLocations = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_LOCATIONS);

            try
            {
                object currentID = hklmLocations.GetValue("CurrentID");
                if (currentID == null)
                {
                    return(String.Empty);
                }
                IRegistryKey currentLocation = hklmLocations.OpenSubKey("Location" + currentID);
                object       areaCode        = currentLocation.GetValue("AreaCode");
                if (areaCode == null)
                {
                    return(String.Empty);
                }

                return(areaCode.ToString());
            }
            catch { return(String.Empty); }
        }
Example #17
0
        public string GetCountryName(int countryID)
        {
            string result = "";

            IRegistryKey hklmCountry = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_COUNTRYLIST_LEGACY);

            if (hklmCountry == null)
            {
                hklmCountry = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_COUNTRYLIST_MODERN);
            }
            if (hklmCountry == null)
            {
                return(String.Empty);
            }

            try
            {
                hklmCountry = hklmCountry.OpenSubKey(countryID.ToString());
                result      = hklmCountry.GetValue("Name").ToString();
            }
            catch { }

            return(result);
        }
        /// <summary>
        /// Prints a registry key with the given depth.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="depth">The depth.</param>
        /// <returns>The key, printed at the given depth.</returns>
        private static string PrintKey(IRegistryKey key, int depth)
        {
            var indent = new string(' ', depth *3);

            //  Get the value strings.
            var values = key.GetValueNames()
                         .Select(v => $"{indent}{(string.IsNullOrEmpty(v) ? "(Default)" : v)} = {key.GetValue(v)}")
                         .OrderBy(s => s);

            //  Get the subkey strings.
            var subKeys = key.GetSubKeyNames()
                          .OrderBy(sk => sk)
                          .Select(sk =>
                                  $"{indent}{sk}{Environment.NewLine}{PrintKey(key.OpenSubKey(sk), depth + 1)}");

            return(string.Join(Environment.NewLine, values.Concat(subKeys)));
        }
Example #19
0
        /// <summary>
        /// Tries to obtaining the path to the latest version of the SQL LocalDB
        /// native API DLL for the currently executing process.
        /// </summary>
        /// <param name="fileName">
        /// When the method returns, contains the path to the SQL Local DB API
        /// to use, if found; otherwise <see langword="null"/>.
        /// </param>
        /// <returns>
        /// <see langword="true"/> if the native API path was successfully found;
        /// otherwise <see langword="false"/>.
        /// </returns>
        internal bool TryGetLocalDbApiPath(out string fileName)
        {
            fileName = null;

            string       keyName = DeriveLocalDbRegistryKey();
            IRegistryKey key     = Registry.OpenSubKey(keyName);

            if (key == null)
            {
                Logger.RegistryKeyNotFound(keyName);
                return(false);
            }

            Version latestVersion   = null;
            Version overrideVersion = null;
            string  path            = null;

            try
            {
                // Is there a setting overriding the version to load?
                string overrideVersionString = ApiVersion;

                foreach (string versionString in key.GetSubKeyNames())
                {
                    if (!Version.TryParse(versionString, out Version version))
                    {
                        Logger.InvalidRegistryKey(versionString);
                        continue;
                    }

                    if (!string.IsNullOrEmpty(overrideVersionString) &&
                        overrideVersion == null &&
                        string.Equals(versionString, overrideVersionString, StringComparison.OrdinalIgnoreCase))
                    {
                        Logger.NativeApiVersionOverriddenByUser(version);
                        overrideVersion = version;
                    }

                    if (latestVersion == null ||
                        latestVersion < version)
                    {
                        latestVersion = version;
                    }
                }

                if (!string.IsNullOrEmpty(overrideVersionString) && overrideVersion == null)
                {
                    Logger.NativeApiVersionOverrideNotFound(overrideVersionString);
                }

                Version versionToUse = overrideVersion ?? latestVersion;

                if (versionToUse != null)
                {
                    using (IRegistryKey subkey = key.OpenSubKey(versionToUse.ToString()))
                    {
                        path = subkey.GetValue("InstanceAPIPath");
                    }

                    NativeApiVersion = versionToUse;
                }
            }
            finally
            {
                key.Dispose();
            }

            if (string.IsNullOrEmpty(path))
            {
                Logger.NativeApiNotFound();
                return(false);
            }

            if (!File.Exists(path))
            {
                Logger.NativeApiLibraryNotFound(path);
                return(false);
            }

            fileName = Path.GetFullPath(path);
            return(true);
        }
        /// <summary>
        /// Saves the active changes to the current theme.
        ///
        /// This is needed to be performed before enabling high-contrast because when high-contrast is de-activated it
        /// loads the settings (such as the wallpaper) from the last used .theme file, rather than the applied settings.
        ///
        /// These means, any unsaved theme customisations will be lost.
        ///
        /// Theme files are described in https://docs.microsoft.com/en-us/windows/desktop/controls/themesfileformat-overview
        /// </summary>
        /// <param name="currentThemeFile">
        /// The current theme file used by the OS. This will be used as a base to create a new theme file, and currently
        /// applied settings will be added to it.</param>
        /// <param name="saveAs">The file to write the saved theme to.</param>
        private async Task SaveCurrentTheme(string currentThemeFile, string saveAs)
        {
            this.logger.LogInformation($"Saving current theme, using {currentThemeFile}.");

            bool isValid = false;
            Dictionary <string, string>?themeData = null;

            try
            {
                // Read the .theme file that's currently being used.
                Ini themeReader = new();
                await themeReader.ReadFile(currentThemeFile);

                themeData = themeReader.ReadData();
                isValid   = themeData.ContainsKey("MasterThemeSelector.MTSM");
            }
            catch (IOException e)
            {
                this.logger.LogInformation(e, $"Unable to read {currentThemeFile}.");
            }

            if (!isValid || themeData is null)
            {
                string defaultTheme = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                                                   "resources\\Themes\\aero.theme");
                if (currentThemeFile != defaultTheme)
                {
                    // OBSERVATION: this code is re-entrant; also note that if the aero.theme file is corrupt...this might reenter infinitely until the stack was full
                    await this.SaveCurrentTheme(defaultTheme, saveAs);
                }
                return;
            }
            else if (themeData.ContainsKey("VisualStyles.HighContrast"))
            {
                // Only save the current theme if it is not high-contrast.
                return;
            }

            using IRegistryKey hKeyCurrentUser =
                      this.registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);

            // Wallpaper
            using IRegistryKey desktopKey = hKeyCurrentUser.OpenSubKey(@"Control Panel\Desktop", false);

            themeData["Theme.DisplayName"] = "morphic";

            themeData["Control Panel\\Desktop.Wallpaper"] =
                desktopKey.GetValue("WallPaper")?.ToString() ?? string.Empty;
            themeData["Control Panel\\Desktop.TileWallpaper"] =
                desktopKey.GetValue("TileWallPaper")?.ToString() ?? string.Empty;
            themeData["Control Panel\\Desktop.WallpaperStyle"] =
                desktopKey.GetValue("WallPaperStyle")?.ToString() ?? string.Empty;

            using IRegistryKey wallpapersKey =
                      hKeyCurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Wallpapers");
            string?backgroundType = wallpapersKey.GetValue("backgroundType")?.ToString();

            if (backgroundType != "2")
            {
                // It's not a slide-show, remove the entire section.
                themeData.Keys.Where(k => k.StartsWith("Slideshow"))
                .ToList()
                .ForEach(k => themeData.Remove(k));
            }

            // Colours
            using IRegistryKey colorsKey = hKeyCurrentUser.OpenSubKey(@"Control Panel\Colors");
            foreach (string valueName in colorsKey.GetValueNames())
            {
                if (colorsKey.GetValue(valueName, null) is string value)
                {
                    themeData[$"Control Panel\\Colors.{valueName}"] = value;
                }
            }

            // if the directory for the saveAs file doesn't exist, create it now
            var saveAsPath = Path.GetDirectoryName(saveAs);

            if (Directory.Exists(saveAsPath) == false)
            {
                Directory.CreateDirectory(saveAsPath);
            }

            Ini writer = new();
            await writer.ReadFile(currentThemeFile);

            writer.WriteData(themeData !);
            await writer.WriteFile(saveAs);

            // Make windows use this theme file when restoring high-contrast.
            using IRegistryKey highContrastKey =
                      hKeyCurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\HighContrast");
            highContrastKey.SetValue("Pre-High Contrast Scheme", saveAs);
        }
Example #21
0
 private static string GetRCurrentVersionStringFromRegistry(IRegistryKey rCoreKey)
 {
     return(rCoreKey.GetValue("Current Version") as string);
 }