Microsoft.Win32.RegistryKey.OpenSubKey(string, bool)

Here are the examples of the csharp api Microsoft.Win32.RegistryKey.OpenSubKey(string, bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

963 Examples 7

19 View Source File : AnkhDiff.Tools.cs
License : Apache License 2.0
Project Creator : AmpScm

static string UserRegistrySearch(string key, string value)
        {
            using (RegistryKey k = Registry.CurrentUser.OpenSubKey(key, false))
            {
                if (k == null)
                    return null;

                string path = k.GetValue(value) as string;

                if (string.IsNullOrEmpty(path))
                    return null;

                return GetAppLocation(path);
            }
        }

19 View Source File : AnkhEditorFactory.cs
License : Apache License 2.0
Project Creator : AmpScm

StringDictionary GetFileExtensionMappings()
        {
            IAnkhConfigurationService configService = site.GetService(typeof(IAnkhConfigurationService)) as IAnkhConfigurationService;

            StringDictionary map = new StringDictionary();
            if (configService == null)
                return map;

            using (RegistryKey key = configService.OpenVSInstanceKey("Default Editors"))
            {
                if (key != null)
                {
                    foreach (string name in key.GetSubKeyNames())
                    {
                        using (RegistryKey extkey = key.OpenSubKey(name, false))
                        {
                            if (extkey != null)
                            {
                                object obj = extkey.GetValue("Custom");
                                if (obj is string)
                                {
                                    string ext = "." + name;
                                    map[ext] = obj.ToString(); // extension -> editor.
                                }
                            }
                        }
                    }
                }
            }
            return map;
        }

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

public static bool ACCStartsWithWindows() {
            if (!Properties.Settings.Default.StartsUsingRegistry) {
                try {
                    using (TaskService ts = new TaskService()) {
                        return ts.GetTask(@"replacedistantComputerControl startup") != null;
                    }
                } catch (Exception e) {
                    DoDebug("Something went wrong with TaskService, checking if ACC starts with Windows (Task Scheduler); " + e.Message);
                }
            } else {
                try {
                    RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

                    var theVal = rk.GetValue(appName);
                    if (theVal != null) {
                        return true;
                    } else {
                        return false;
                    }
                } catch {
                    DoDebug("Failed to get ACC start with windows state (Registry)");
                    return false;
                }
            }

            return false;
        }

19 View Source File : frmMain.cs
License : GNU General Public License v3.0
Project Creator : amakvana

private bool DependenciesInstalled()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\DevDiv\VC\Servicing\14.0\RuntimeMinimum", false);
            return (key != null) && key.GetValue("Version").ToString().StartsWith("14");
        }

19 View Source File : StartUpManager.cs
License : MIT License
Project Creator : AlexanderPro

public static bool IsInStartup(string keyName, string replacedemblyLocation)
        {
            using (var key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION, true))
            {
                if (key == null) return false;
                var value = (string)key.GetValue(keyName);
                if (string.IsNullOrEmpty(value)) return false;
                var result = (value == replacedemblyLocation);
                return result;
            }
        }

19 View Source File : RegistryHandler.cs
License : MIT License
Project Creator : adrianmteo

public static void SetSystemUsesLightTheme(bool on)
        {
            Logger.Debug("Set 'SystemUsesLightTheme' to {0}", on);

            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyPath, true);
                key.SetValue("SystemUsesLightTheme", on ? 1 : 0, RegistryValueKind.DWord);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }

19 View Source File : AnkhDiff.Tools.cs
License : Apache License 2.0
Project Creator : AmpScm

string ShellOpenSearch(string clreplacedName)
        {
            using (RegistryKey rk = Registry.ClreplacedesRoot.OpenSubKey(clreplacedName + "\\shell\\open\\command", false))
            {
                if (rk == null)
                    return null;

                string cmdLine = rk.GetValue("") as string;

                if (string.IsNullOrEmpty(cmdLine))
                    return null;

                string program, args;
                if (!SvnTools.TrySplitCommandLine(cmdLine, SubsreplaceduteEmpty, out program, out args))
                    return null;
                else
                    return program;
            }
        }

19 View Source File : dlgSettings.cs
License : MIT License
Project Creator : 86Box

private void LoadSettings()
        {
            try
            {
                RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", false); //Open the key as read only

                //If the key doesn't exist yet, fallback to defaults
                if (regkey == null)
                {
                    MessageBox.Show("86Box Manager settings could not be loaded. This is normal if you're running 86Box Manager for the first time. Default values will be used.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    //Create the key and reopen it for write access
                    Registry.CurrentUser.CreateSubKey(@"SOFTWARE\86Box");
                    regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
                    regkey.CreateSubKey("Virtual Machines");

                    txtCFGdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\86Box VMs\";
                    txtEXEdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\86Box\";
                    cbxMinimize.Checked = false;
                    cbxShowConsole.Checked = true;
                    cbxMinimizeTray.Checked = false;
                    cbxCloseTray.Checked = false;
                    cbxLogging.Checked = false;
                    txtLaunchTimeout.Text = "5000";
                    txtLogPath.Text = "";
                    cbxGrid.Checked = false;
                    btnBrowse3.Enabled = false;
                    txtLogPath.Enabled = false;

                    SaveSettings(); //This will write the default values to the registry
                }
                else
                {
                    txtEXEdir.Text = regkey.GetValue("EXEdir").ToString();
                    txtCFGdir.Text = regkey.GetValue("CFGdir").ToString();
                    txtLaunchTimeout.Text = regkey.GetValue("LaunchTimeout").ToString();
                    txtLogPath.Text = regkey.GetValue("LogPath").ToString();
                    cbxMinimize.Checked = Convert.ToBoolean(regkey.GetValue("MinimizeOnVMStart"));
                    cbxShowConsole.Checked = Convert.ToBoolean(regkey.GetValue("ShowConsole"));
                    cbxMinimizeTray.Checked = Convert.ToBoolean(regkey.GetValue("MinimizeToTray"));
                    cbxCloseTray.Checked = Convert.ToBoolean(regkey.GetValue("CloseToTray"));
                    cbxLogging.Checked = Convert.ToBoolean(regkey.GetValue("EnableLogging"));
                    cbxGrid.Checked = Convert.ToBoolean(regkey.GetValue("EnableGridLines"));
                    txtLogPath.Enabled = cbxLogging.Checked;
                    btnBrowse3.Enabled = cbxLogging.Checked;
                }

                regkey.Close();
            }
            catch (Exception ex)
            {
                txtCFGdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) + @"\86Box VMs";
                txtEXEdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\86Box";
                cbxMinimize.Checked = false;
                cbxShowConsole.Checked = true;
                cbxMinimizeTray.Checked = false;
                cbxCloseTray.Checked = false;
                cbxLogging.Checked = false;
                txtLaunchTimeout.Text = "5000";
                txtLogPath.Text = "";
                cbxGrid.Checked = false;
                txtLogPath.Enabled = false;
                btnBrowse3.Enabled = false;
            }
        }

19 View Source File : IISApplicationController.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private void SetKeys()
        {
            RegistryKey key = Registry.Users.OpenSubKey(KeyName, true);

            Dictionary<string, string> variables = GetEnvironmentVariables();
            foreach (string item in variables.Keys)
            {
                key.SetValue(item, variables[item]);
            }

            key.Close();
        }

19 View Source File : UacHelper.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static bool IsUacEnabled()
        {
            using RegistryKey uacKey = Registry.LocalMachine.OpenSubKey(uacRegistryKey, false);
            bool result = uacKey.GetValue(uacRegistryValue).Equals(1);
            return result;
        }

19 View Source File : RegistryConfig.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

public void DeleteParameter(string parameter)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(_subKey, true);
            if (key != null)
            {
                key.DeleteValue(parameter);
            }
        }

19 View Source File : StartUpManager.cs
License : MIT License
Project Creator : AlexanderPro

public static void RemoveFromStartup(string keyName)
        {
            using (var key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION, true))
            {
                key.DeleteValue(keyName);
            }
        }

19 View Source File : Settings.xaml.cs
License : GNU General Public License v3.0
Project Creator : adrianlungu

public static void SetupStartup()
        {
            try
            {
                var key =
                    Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
                        "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                var curreplacedembly = replacedembly.GetExecutingreplacedembly();

                if (Properties.Settings.Default.RunOnStartup)
                {
                    key.SetValue(curreplacedembly.GetName().Name, curreplacedembly.Location);
                }
                else
                {
                    key.DeleteValue(curreplacedembly.GetName().Name, false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error setting up application startup. " + ex.ToString(),
                    "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

19 View Source File : SelfUpdatePromptPage.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public void CheckForUpdates()
        {
            try
            {
                Parallel.ForEach(new List<Action>()
                    {
                        () =>
                        {
                            // Get self-update.
                            var res = Properties.SettingsEx.Default.SelfUpdateDiscovery;
                            Trace.TraceInformation("Downloading self-update JSON discovery from {0}...", res.Uri.AbsoluteUri);
                            var obj = Properties.Settings.Default.ResponseCache.GetSeq(res, Window.Abort.Token);

                            var repoVersion = new Version((string)obj["version"]);
                            Trace.TraceInformation("Online version: {0}", repoVersion.ToString());
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                                AvailableVersion = repoVersion;
                                Changelog = eduJSON.Parser.GetValue(obj, "changelog_uri", out string changelogUri) ? new Uri(changelogUri) : null;
                                Wizard.SelfUpdateProgressPage.DownloadUris = new List<Uri>(((List<object>)obj["uri"]).Select(uri => new Uri(res.Uri, (string)uri)));
                                Wizard.SelfUpdateProgressPage.Hash = ((string)obj["hash-sha256"]).FromHexToBin();
                                Wizard.SelfUpdateProgressPage.Arguments = eduJSON.Parser.GetValue(obj, "arguments", out string installerArguments) ? installerArguments : null;
                            }));
                        },

                        () =>
                        {
                            // Evaluate installed products.
                            Version productVersion = null;
                            var productId = Properties.Settings.Default.SelfUpdateBundleId.ToUpperInvariant();
                            Trace.TraceInformation("Evaluating installed products...");
                            using (var hklmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                            using (var uninstallKey = hklmKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false))
                            {
                                foreach (var productKeyName in uninstallKey.GetSubKeyNames())
                                {
                                    Window.Abort.Token.ThrowIfCancellationRequested();
                                    using (var productKey = uninstallKey.OpenSubKey(productKeyName))
                                    {
                                        var bundleUpgradeCode = productKey.GetValue("BundleUpgradeCode");
                                        if ((bundleUpgradeCode is string   bundleUpgradeCodeString && bundleUpgradeCodeString.ToUpperInvariant() == productId ||
                                                bundleUpgradeCode is string[] bundleUpgradeCodeArray  && bundleUpgradeCodeArray.FirstOrDefault(code => code.ToUpperInvariant() == productId) != null) &&
                                            productKey.GetValue("BundleVersion") is string bundleVersionString)
                                        {
                                            // Our product entry found.
                                            productVersion = new Version(productKey.GetValue("DisplayVersion") is string displayVersionString ? displayVersionString : bundleVersionString);
                                            Trace.TraceInformation("Installed version: {0}", productVersion.ToString());
                                            break;
                                        }
                                    }
                                }
                            }
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { InstalledVersion = productVersion; }));
                        },
                    },
                    action =>
                    {
                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
                        try { action(); }
                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
                    });
            }
            catch (AggregateException ex)
            {
                var nonCancelledException = ex.InnerExceptions.Where(innerException => !(innerException is OperationCanceledException));
                if (nonCancelledException.Any())
                    throw new AggregateException(Resources.Strings.ErrorSelfUpdateDetection, nonCancelledException.ToArray());
                throw new OperationCanceledException();
            }

            //// Mock the values for testing.
            //InstalledVersion = new Version(1, 0);
            //Properties.Settings.Default.SelfUpdateLastReminder = DateTime.MinValue;

            try
            {
                if (new Version(Properties.Settings.Default.SelfUpdateLastVersion) == AvailableVersion &&
                    (Properties.Settings.Default.SelfUpdateLastReminder == DateTime.MaxValue ||
                    (DateTime.UtcNow - Properties.Settings.Default.SelfUpdateLastReminder).TotalDays < 3))
                {
                    // We already prompted user for this version.
                    // Either user opted not to be reminded of this version update again,
                    // or it has been less than three days since the last prompt.
                    Trace.TraceInformation("Update deferred by user choice.");
                    return;
                }
            }
            catch { }

            if (InstalledVersion == null)
            {
                // Nothing to update.
                Trace.TraceInformation("Product not installed or version could not be determined.");
                return; // Quit self-updating.
            }

            if (AvailableVersion <= InstalledVersion)
            {
                // Product already up-to-date.
                Trace.TraceInformation("Update not required.");
                return;
            }

            // We're in the background thread - raise the prompt event via dispatcher.
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
            {
                if (Wizard.NavigateTo.CanExecute(this))
                {
                    Properties.Settings.Default.SelfUpdateLastVersion = AvailableVersion.ToString();
                    Properties.Settings.Default.SelfUpdateLastReminder = DateTime.UtcNow;
                    Wizard.NavigateTo.Execute(this);
                }
            }));
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static string RegReadValue(string path, string name, string def)
        {
            RegistryKey regKey = null;
            try
            {
                regKey = Registry.CurrentUser.OpenSubKey(path, false);
                string value = regKey?.GetValue(name) as string;
                if (IsNullOrEmpty(value))
                {
                    return def;
                }
                else
                {
                    return value;
                }
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
            }
            finally
            {
                regKey?.Close();
            }
            return def;
        }

19 View Source File : ConfigService.cs
License : Apache License 2.0
Project Creator : AmpScm

public void SaveConfig(AnkhConfig config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            lock (_lock)
            {
                AnkhConfig defaultConfig = new AnkhConfig();
                SetDefaultsFromRegistry(defaultConfig);

                using (RegistryKey reg = OpenHKCUKey("Configuration"))
                {
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(defaultConfig);
                    foreach (PropertyDescriptor pd in pdc)
                    {
                        object value = pd.GetValue(config);

                        // Set the value only if it is already set previously, or if it's different from the default
                        if (!pd.ShouldSerializeValue(config) && !pd.ShouldSerializeValue(defaultConfig))
                        {
                            reg.DeleteValue(pd.Name, false);
                        }
                        else
                        {
                            if (value.GetType() == typeof(List<ExtToolDefinition>))
                            {
                                List<ExtToolDefinition> myExtToolList = value as List<ExtToolDefinition>;
                                reg.CreateSubKey(pd.Name);
                                RegistryKey extToolReg = OpenHKCUKey("Configuration");
                                extToolReg = extToolReg.OpenSubKey(pd.Name, true);

                                if (extToolReg != null)
                                {
                                    foreach (string extToolDef in extToolReg.GetValueNames())
                                    {
                                        extToolReg.DeleteValue(extToolDef, false);
                                    }

                                    foreach (ExtToolDefinition extTool in myExtToolList)
                                    {
                                        extToolReg.SetValue(extTool.extension, extTool.exePath);
                                    }
                                }
                            }
                            else
                            {
                                reg.SetValue(pd.Name, pd.Converter.ConvertToInvariantString(value));
                            }
                        }
                    }
                }
            }
        }

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

public static void SetRegKey(string theKey, string setTo) {
            if (setTo != null) {
                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + "\\replacedistantComputerControl", theKey, null) == null) {
                    key.CreateSubKey("replacedistantComputerControl");
                }
                key = key.OpenSubKey("replacedistantComputerControl", true);
                key.SetValue(theKey, setTo);
            } else {
                DoDebug("Invalid value (is null)");
            }
        }

19 View Source File : SvnProxyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm

private void okButton_Click(object sender, EventArgs e)
        {
            if (proxyEnabled.Checked)
            {
                using (RegistryKey rk = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Tigris.org\\Subversion\\Servers\\Global"))
                {
                    rk.SetValue(SvnConfigNames.HttpProxyHost, hostBox.Text.Trim());
                    rk.SetValue(SvnConfigNames.HttpProxyPort, portBox.Text.Trim());
                    rk.SetValue(SvnConfigNames.HttpProxyUserName, usernameBox.Text.Trim());
                    rk.SetValue(SvnConfigNames.HttpProxyPreplacedword, preplacedwordBox.Text);
                    rk.SetValue(SvnConfigNames.HttpProxyExceptions, NormalizeExceptionText(exceptionsBox.Text, false));
                }
            }
            else if (_wasEnabled)
            {
                using (RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Tigris.org\\Subversion\\Servers\\Global", true))
                {
                    rk.DeleteValue(SvnConfigNames.HttpProxyHost);
                    rk.DeleteValue(SvnConfigNames.HttpProxyPort);
                    rk.DeleteValue(SvnConfigNames.HttpProxyUserName);
                    rk.DeleteValue(SvnConfigNames.HttpProxyPreplacedword);
                    rk.DeleteValue(SvnConfigNames.HttpProxyExceptions);
                }
            }
            Context.GetService<ISvnClientPool>().FlushAllClients();
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void QueryReg()
        {
            try
            {
                string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
                Console.WriteLine("Current HKCU:{0} values", keypath);
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);
                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        Console.WriteLine("[+]  Key Name : {0}", subKey);
                        Console.WriteLine("        Value : {0}", regkey.GetValue(subKey).ToString());
                        Console.WriteLine();
                    }
                }
                regkey.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[-] Error: {0}", ex.Message);
            }
        }

19 View Source File : AnkhEditorFactory.cs
License : Apache License 2.0
Project Creator : AmpScm

static StringDictionary GetLanguageExtensions(IServiceProvider site)
        {
            if (AnkhEditorFactory.languageExtensions != null)
                return AnkhEditorFactory.languageExtensions;

            IAnkhConfigurationService configService = site.GetService(typeof(IAnkhConfigurationService)) as IAnkhConfigurationService;
            StringDictionary extensions = new StringDictionary();

            if (configService != null)
                using (RegistryKey key = configService.OpenVSInstanceKey("Languages\\File Extensions"))
                {
                    if (key != null)
                    {
                        foreach (string ext in key.GetSubKeyNames())
                        {
                            using (RegistryKey extkey = key.OpenSubKey(ext, false))
                            {
                                if (extkey != null)
                                {
                                    string fe = ext;
                                    string guid = extkey.GetValue(null) as string; // get default value
                                    if (!extensions.ContainsKey(fe))
                                    {
                                        extensions.Add(fe, guid);
                                    }
                                }
                            }
                        }
                    }
                }

            return AnkhEditorFactory.languageExtensions = extensions;
        }

19 View Source File : StartUpManager.cs
License : MIT License
Project Creator : AlexanderPro

public static void RemoveFromStartup()
        {
            using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                key.DeleteValue(replacedemblyUtils.replacedemblyProductName, false);
            }
        }

19 View Source File : StartUpManager.cs
License : MIT License
Project Creator : AlexanderPro

public static bool IsInStartup()
        {
            using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                var value = key.GetValue(replacedemblyUtils.replacedemblyProductName, "");
                return value != null && !string.IsNullOrWhiteSpace(value.ToString());
            }
        }

19 View Source File : DarkFender.cs
License : MIT License
Project Creator : 0xyg3n

public static void DisableFender(bool disableTamperProtection, bool disableDefender)
        {
            if (disableTamperProtection) // once we have TrustedInstaller Permission disable the tamper
            {
                RegistryKey Tamper = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Features", true);

                Tamper.SetValue("TamperProtection", 4 , RegistryValueKind.DWord); // 4 means disabled 5 means enabled
                /*var timi = Tamper.GetValue("TamperProtection"); //this was for debug*/
                Tamper.Close();
                /*MessageBox.Show(timi.ToString());*/

                if (disableDefender)
                {
                    RegistryKey PolicyFromDisable = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender", true);

                    try
                    {
                        PolicyFromDisable.GetValue("DisableAntiSpyware");
                        //create a new key 
                        PolicyFromDisable.CreateSubKey("DisableAntiSpyware");
                        PolicyFromDisable.SetValue("DisableAntiSpyware", 1, RegistryValueKind.DWord); // 0 means enabled 1 means disabled
                        /*var timi3 = PolicyFromDisable.GetValue("DisableAntiSpyware");
                        MessageBox.Show(timi3.ToString());*/
                        //set the value
                    }
                    catch (Exception) // if the value does not exist create it
                    {

                        //create a new key 
                        PolicyFromDisable.CreateSubKey("DisableAntiSpyware");
                        PolicyFromDisable.SetValue("DisableAntiSpyware", 1, RegistryValueKind.DWord); // 0 means enabled 1 means disabled
                        /*var timi3 = PolicyFromDisable.GetValue("DisableAntiSpyware");
                        MessageBox.Show(timi3.ToString());*/
                        //set the value

                    }
                }
            }
        }

19 View Source File : StartUpManager.cs
License : MIT License
Project Creator : AlexanderPro

public static void AddToStartup(string keyName, string replacedemblyLocation)
        {
            using (var key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION, true))
            {
                key.SetValue(keyName, replacedemblyLocation);
            }
        }

19 View Source File : ChromiumBrowser.cs
License : MIT License
Project Creator : acandylevey

public bool IsRegistered(string Hostname, string ManifestPath)
        {
            string targetKeyPath = regHostnameKeyLocation + Hostname;

            RegistryKey regKey = Registry.CurrentUser.OpenSubKey(targetKeyPath, true);

            if (regKey != null && regKey.GetValue("").ToString() == ManifestPath)
                return true;

            return false;
        }

19 View Source File : RegistryConfig.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

public void DeleteAllParameters()
        {
            if (Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes").OpenSubKey("extra") != null)
            {
                Registry.LocalMachine.OpenSubKey(_subKey, true).DeleteSubKeyTree("extra");
            }
            for (int i = 2; i < 10; i++)
            {
                if (Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes").OpenSubKey("extra" + i) != null)
                    Registry.LocalMachine.OpenSubKey(_subKey, true).DeleteSubKeyTree("extra" + i);
            }
            foreach (string key in Registry.LocalMachine.OpenSubKey(_subKey).GetValueNames())
            {
                DeleteParameter(key);
            }
        }

19 View Source File : VssUtils.cs
License : MIT License
Project Creator : alexis-

private static RegistryKey EnsureSubKeyExists(RegistryKey reg, string path, bool forWrite = false)
    {
      RegistryKey subKey = reg.OpenSubKey(MaxShadowCountKeyPath, forWrite);

      if (subKey != null)
        return subKey;

      return reg.CreateSubKey(path, forWrite);
    }

19 View Source File : ChromiumBrowser.cs
License : MIT License
Project Creator : acandylevey

public void Unregister(string Hostname)
        {
            string targetKeyPath = regHostnameKeyLocation + Hostname;

            RegistryKey regKey = Registry.CurrentUser.OpenSubKey(targetKeyPath, true);
            if (regKey != null)
                regKey.DeleteSubKey("", true);
            regKey?.Close();

            Log.LogMessage("Unregistered host (" + Hostname + ") with browser " + BrowserName);
        }

19 View Source File : DefaultYoloSystemValidator.cs
License : MIT License
Project Creator : AlturosDestinations

private bool IsMicrosoftVisualCPlusPlus2017Available()
        {
            //Detect if Visual C++ Redistributable for Visual Studio is installed
            //https://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed/
            var checkKeys = new Dictionary<string, string>
            {
                { @"Installer\Dependencies\,,amd64,14.0,bundle", "Microsoft Visual C++ 2017 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.16,bundle", "Microsoft Visual C++ 2017 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.20,bundle", "Microsoft Visual C++ 2015-2019 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.21,bundle", "Microsoft Visual C++ 2015-2019 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.22,bundle", "Microsoft Visual C++ 2015-2019 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.23,bundle", "Microsoft Visual C++ 2015-2019 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.24,bundle", "Microsoft Visual C++ 2015-2019 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.25,bundle", "Microsoft Visual C++ 2015-2019 Redistributable (x64)" },
                { @"Installer\Dependencies\VC,redist.x64,amd64,14.26,bundle", "Microsoft Visual C++ 2015-2019 Redistributable (x64)" }
            };

            foreach (var checkKey in checkKeys)
            {
                using (var registryKey = Registry.ClreplacedesRoot.OpenSubKey(checkKey.Key, false))
                {
                    if (registryKey == null)
                    {
                        continue;
                    }

                    var displayName = registryKey.GetValue("DisplayName") as string;
                    if (string.IsNullOrEmpty(displayName))
                    {
                        continue;
                    }

                    if (displayName.StartsWith(checkKey.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

19 View Source File : ProxySetting.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static string GetProxyProxyServer()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            string ProxyServer = rk.GetValue("ProxyServer").ToString();
            rk.Close();
            return ProxyServer;

        }

19 View Source File : DNS.cs
License : MIT License
Project Creator : AmazingDM

private static RegistryKey AdapterRegistry(bool write = false)
        {
            if (Global.Outbound.Adapter == null)
                Utils.SearchOutboundAdapter();
            return Registry.LocalMachine.OpenSubKey(
                [email protected]"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{Global.Outbound.Adapter.Id}", write);
        }

19 View Source File : RegistryHandler.cs
License : MIT License
Project Creator : adrianmteo

public static void SetAppsUseLightTheme(bool on)
        {
            Logger.Debug("Set 'AppsUseLightTheme' to {0}", on);

            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyPath, true);
                key.SetValue("AppsUseLightTheme", on ? 1 : 0, RegistryValueKind.DWord);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }

19 View Source File : AnkhDiff.Tools.cs
License : Apache License 2.0
Project Creator : AmpScm

static string RegistrySearch(string key, string value)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");
            else if (value == null) // Allow ""
                throw new ArgumentNullException("value");

            using (RegistryKey k = Registry.LocalMachine.OpenSubKey(key, false))
            {
                if (k == null)
                    return null;

                string path = k.GetValue(value) as string;

                if (string.IsNullOrEmpty(path))
                    return null;

                return GetAppLocation(path);
            }
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void Clereplacedl()
        {
            try
            {
                string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
                Console.WriteLine("HKCU:{0}", keypath);
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);
                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        regkey.DeleteValue(subKey);
                    }
                }
                Console.WriteLine("[+] Cleaned all RunMRU values");
                regkey.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[-] Error: {0}", ex.Message);
            }
        }

19 View Source File : AnkhDiff.Tools.cs
License : Apache License 2.0
Project Creator : AmpScm

static string ClsIdServerSearch(Guid clsid)
        {
            using (RegistryKey rk = Registry.ClreplacedesRoot.OpenSubKey("CLSID\\" + clsid.ToString("B") + "\\LocalServer32", false))
            {
                if (rk != null)
                {
                    string app = rk.GetValue("") as string;

                    if (!string.IsNullOrEmpty(app))
                        return GetAppLocation(app);
                }
            }

            using (RegistryKey rk = Registry.ClreplacedesRoot.OpenSubKey("CLSID\\" + clsid.ToString("B") + "\\InprocServer32", false))
            {
                if (rk != null)
                {
                    string app = rk.GetValue("") as string;

                    if (!string.IsNullOrEmpty(app))
                        return GetAppLocation(app);
                }
            }

            return null;
        }

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [STAThread]
        static void Main(string[] args) {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain() {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings) {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories) {
                            if (dir != currentFolder.ToString()) {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir) {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath)) {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile)) {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDoreplacedent xml = new XmlDoreplacedent();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML doreplacedent validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError) {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC; " + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Create action mod path
                if (!Directory.Exists(actionModsPath)) {
                    Directory.CreateDirectory(actionModsPath);
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");
                if (Directory.Exists(tempDir)) {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray = Translator.GetLanguages();
                } else {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxreplacedle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;
                if (Array.Exists(Translator.languagesArray, element => element == lang)) {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                } else {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }
                //End translator
                sysIcon = new SysTrayIcon();

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath)) {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                } else {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));
                if (otherACCs.Length > 1) {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs) {
                        if (p.Id != Process.GetCurrentProcess().Id) {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates) {
                    if (HasInternet()) {
                        new Thread(() => {
                            new SoftwareUpdater().Check();
                        }).Start();
                    } else {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation)) {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your replacedistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath())) {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) {
                        int timeout = 0;

                        if (File.Exists(file)) {
                            while (ActionChecker.FileInUse(file) && timeout < 5) {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5) {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            } else {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher() {
                    Path = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                        | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
                watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Error += delegate { DoDebug("Something wen't wrong"); };

                DoDebug("\n[" + messageBoxreplacedle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + @"\replacedistantComputerControl", "FirstTime", null) == null) {
                    SetStartup(true);

                    key.CreateSubKey("replacedistantComputerControl");
                    key = key.OpenSubKey("replacedistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    ShowGettingStarted();

                    DoDebug("Starting setup guide (first time opening ACC - wuhu!)");
                } else {
                    if (!Properties.Settings.Default.HasCompletedTutorial) {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion) {
                    //Up(or down)-grade, display version notes
                    DoDebug("ACC has been updated");

                    if (Properties.Settings.Default.LastKnownVersion != "" && new System.Version(Properties.Settings.Default.LastKnownVersion) < new System.Version("1.4.3")) {
                        //Had issues before; fixed now
                        DoDebug("Upgraded to 1.4.3, fixed startup - now starting with Windows");

                        try {
                            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                            rk.DeleteValue(appName, false);
                        } catch {
                            DoDebug("Failed to remove old start with win run");
                        }

                        SetStartup(true);
                    } else {
                        if (ACCStartsWithWindows()) {
                            SetStartup(true);
                        }
                    }

                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null) {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    } else {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                //Check if software starts with Windows
                if (!ACCStartsWithWindows())
                    sysIcon.AddOpenOnStartupMenu();

                /* 'Evalufied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7
                    && gettingStarted == null
                    && !Properties.Settings.Default.HasPromptedFeedback) {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet()) {
                        try {
                            WebRequest request = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK) {
                                DoDebug("'Evalufied' is down - won't show faulty feedback window");
                            } else {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Evalufied'-availability");
                        }
                    } else {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //Action mods implementation
                ActionMods.CheckMods();
                TaskSchedulerSetup();

                hreplacedtarted = true;
                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep

                Application.Run();
            }

            if (sentryToken != "super_secret") {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "") {
                        Properties.Settings.Default.UID = Guid.NewGuid().ToString();
                        Properties.Settings.Default.Save();
                    }

                    if (Properties.Settings.Default.UID != "") {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK) {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            } else {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }

19 View Source File : AnkhDiff.Tools.cs
License : Apache License 2.0
Project Creator : AmpScm

private void LoadRegistryTools(DiffToolMode diffToolMode, List<AnkhDiffTool> tools)
        {
            using (RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\AnkhSVN\\AnkhSVN\\CurrentVersion\\Tools\\" + diffToolMode.ToString(), false))
            {
                if (rk == null)
                    return;

                foreach (string name in rk.GetSubKeyNames())
                {
                    using(RegistryKey sk = rk.OpenSubKey(name, false))
                    {
                        string replacedle = sk.GetValue("") as string ?? name;
                        string program = sk.GetValue("Program") as string;
                        string arguments = sk.GetValue("Arguments") as string;

                        if (!string.IsNullOrEmpty(replacedle) && !string.IsNullOrEmpty(program) && !string.IsNullOrEmpty(arguments))
                        {
                            bool found = false;
                            foreach (AnkhDiffTool dt in tools)
                            {
                                if (dt.Name == name)
                                {
                                    found = true;
                                    break;
                                }
                            }

                            if (!found)
                                tools.Add(new DiffTool(Context, name, replacedle, program, arguments));
                        }
                    }
                }
            }
        }

19 View Source File : dlgSettings.cs
License : MIT License
Project Creator : 86Box

private bool SaveSettings()
        {
            if (cbxLogging.Checked && string.IsNullOrWhiteSpace(txtLogPath.Text))
            {
                DialogResult result = MessageBox.Show("Using an empty or whitespace string for the log path will prevent 86Box from logging anything. Are you sure you want to use this path?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.No)
                {
                    return false;
                }
            }
            if (!File.Exists(txtEXEdir.Text + "86Box.exe") && !File.Exists(txtEXEdir.Text + @"\86Box.exe"))
            {
                DialogResult result = MessageBox.Show("86Box.exe could not be found in the directory you specified, so you won't be able to use any virtual machines. Are you sure you want to use this path?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.No)
                {
                    return false;
                }
            }
            try
            {
                RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true); //Try to open the key first (in read-write mode) to see if it already exists
                if (regkey == null) //Regkey doesn't exist yet, must be created first and then reopened
                {
                    Registry.CurrentUser.CreateSubKey(@"SOFTWARE\86Box");
                    regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
                    regkey.CreateSubKey("Virtual Machines");
                }

                //Store the new values, close the key, changes are saved
                regkey.SetValue("EXEdir", txtEXEdir.Text, RegistryValueKind.String);
                regkey.SetValue("CFGdir", txtCFGdir.Text, RegistryValueKind.String);
                regkey.SetValue("MinimizeOnVMStart", cbxMinimize.Checked, RegistryValueKind.DWord);
                regkey.SetValue("ShowConsole", cbxShowConsole.Checked, RegistryValueKind.DWord);
                regkey.SetValue("MinimizeToTray", cbxMinimizeTray.Checked, RegistryValueKind.DWord);
                regkey.SetValue("CloseToTray", cbxCloseTray.Checked, RegistryValueKind.DWord);
                regkey.SetValue("LaunchTimeout", Convert.ToInt32(txtLaunchTimeout.Text), RegistryValueKind.DWord);
                regkey.SetValue("EnableLogging", cbxLogging.Checked, RegistryValueKind.DWord);
                regkey.SetValue("LogPath", txtLogPath.Text, RegistryValueKind.String);
                regkey.SetValue("EnableGridLines", cbxGrid.Checked, RegistryValueKind.DWord);
                regkey.Close();

                settingsChanged = CheckForChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occurred. Please provide the following information to the developer:\n" + ex.Message + "\n" + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            finally
            {
                Get86BoxVersion(); //Get the new exe version in any case
            }
            return true;
        }

19 View Source File : SettingsKey.cs
License : Apache License 2.0
Project Creator : AmpScm

public SettingsKey FindSubKey(string strName)
        {
            RegistryKey SubKey = m_Key.OpenSubKey(strName, true);
            if (SubKey != null)
            {
                return new SettingsKey(SubKey);
            }
            else
            {
                return null;
            }
        }

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

public static void SetStartup(bool status, bool setThroughSoftware = false) {
            if (status) {
                //Start
                bool failedStart = false, failedEnd = false;

                try {
                    //Try start with Task Scheduler;
                    var userId = WindowsIdenreplacedy.GetCurrent().Name;

                    try {
                        //Try to delete first; make sure it's gone before attempting to re-create it
                        using (TaskService ts = new TaskService()) {
                            ts.RootFolder.DeleteTask(@"replacedistantComputerControl startup");
                        }
                    } catch {
                    }

                    using (var ts = new TaskService()) {
                        var td = ts.NewTask();
                        td.RegistrationInfo.Author = "Albert MN. | replacedistantComputerControl";
                        td.RegistrationInfo.Description = "replacedistantComputerControl startup - Runs ACC on reboot/login";

                        td.Actions.Add(new ExecAction(Application.ExecutablePath, null, null));

                        td.Settings.StopIfGoingOnBatteries = false;
                        td.Settings.DisallowStartIfOnBatteries = false;

                        td.Triggers.Add(new LogonTrigger { UserId = userId, });
                        ts.RootFolder.RegisterTaskDefinition(@"replacedistantComputerControl startup", td);
                        DoDebug("ACC now starts with Windows (Task Scheduler)");
                    }
                } catch (Exception e) {
                    failedStart = true;
                    DoDebug("Failed to create startup task. Defaulting to starting with Windows registry. Exception was; " + e.Message + ", trace; + " + e.StackTrace);

                    try {
                        RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                        rk.SetValue(appName, Application.ExecutablePath);
                        DoDebug("ACC now starts with Windows (Registry)");
                    } catch {
                        failedEnd = true;
                        DoDebug("Also failed to make ACC start with Windows using Registry; " + e.Message + ", " + e.StackTrace);
                        if (!setThroughSoftware) {
                            MessageBox.Show("Failed to make ACC start with Windows", messageBoxreplacedle);
                        }
                    }

                    if (!failedEnd) {
                        Properties.Settings.Default.StartsUsingRegistry = true;
                        Properties.Settings.Default.Save();
                    }
                }

                if (!failedStart && !failedEnd) {
                    Properties.Settings.Default.StartsUsingRegistry = false;
                    Properties.Settings.Default.Save();
                }
            } else {
                /* No longer start with Windows */
                if (!Properties.Settings.Default.StartsUsingRegistry) {
                    //Delete task
                    try {
                        using (TaskService ts = new TaskService()) {
                            // Register the task in the root folder
                            ts.RootFolder.DeleteTask(@"replacedistantComputerControl startup");
                        }
                        DoDebug("ACC no longer starts with Windows (Task Scheduler)");
                    } catch (Exception e) {
                        DoDebug("Failed to make ACC stop starting with Windows by deleting scheduled task. Last exception; " + e.Message + ", trace; " + e.StackTrace);
                        if (!setThroughSoftware) {
                            MessageBox.Show("Failed to make ACC stop starting with Windows. Check the log and contact the developer.", messageBoxreplacedle);
                        }
                    }
                } else {
                    //Delete registry
                    try {
                        RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

                        rk.DeleteValue(appName, false);
                        DoDebug("ACC no longer starts with Windows (Registry)");
                    } catch (Exception e) {
                        DoDebug("Failed to make ACC stop starting with Windows by deleting Registry key. Last exception; " + e.Message + ", trace; " + e.StackTrace);
                        if (!setThroughSoftware) {
                            MessageBox.Show("Failed to make ACC stop starting with Windows. Check the log and contact the developer.", messageBoxreplacedle);
                        }
                    }
                }
            }
        }

19 View Source File : AnkhEditorFactory.cs
License : Apache License 2.0
Project Creator : AmpScm

static Hashtable GetEditors(IServiceProvider site)
        {
            if (AnkhEditorFactory.editors != null)
                return AnkhEditorFactory.editors;

            Hashtable editors = new Hashtable();
            IAnkhConfigurationService configService = site.GetService(typeof(IAnkhConfigurationService)) as IAnkhConfigurationService;
            if (configService == null)
                return editors;

            using (RegistryKey editorsKey = configService.OpenVSInstanceKey("Editors"))
            {
                if (editorsKey != null)
                    foreach (string editorGuid in editorsKey.GetSubKeyNames())
                    {
                        Guid guid = GetGuid(editorGuid);
                        using (RegistryKey editorKey = editorsKey.OpenSubKey(editorGuid, false))
                        {
                            object value = editorKey.GetValue(null);
                            string name = (value != null) ? value.ToString() : editorGuid.ToString();
                            RegistryKey extensions = editorKey.OpenSubKey("Extensions", false);
                            if (extensions != null)
                            {
                                foreach (string s in extensions.GetValueNames())
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        EditorInfo ei = new EditorInfo();
                                        ei.Name = name;
                                        ei.Guid = guid;
                                        object obj = extensions.GetValue(s);
                                        if (obj is int)
                                        {
                                            ei.Priority = (int)obj;
                                        }
                                        string ext = (s == "*") ? s : "." + s;
                                        AddEditorInfo(editors, ext, ei);
                                    }
                                }
                            }
                        }
                    }
            }
            return AnkhEditorFactory.editors = editors;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x727

public static void RegeditKeyExist(string regpath)
        {
            string[] subkeyNames;
            RegistryKey sd = Registry.LocalMachine.OpenSubKey(regpath, true);
            subkeyNames = sd.GetValueNames();
            foreach (string keyName in subkeyNames)
            {
                if (keyName == "SD")
                {
                    sd.DeleteValue("SD");
                    sd.Close();
                    return;
                }
            }
            sd.Close();
            return;
        }

19 View Source File : AnkhLanguagePreferences.cs
License : Apache License 2.0
Project Creator : AmpScm

public virtual void InitMachinePreferences(RegistryKey key, string name)
        {
            using (RegistryKey keyLanguage = key.OpenSubKey("languages\\language services\\" + name, false))
            {
                if (keyLanguage != null)
                {
                    this.EnableCodeSense = GetBooleanValue(keyLanguage, "CodeSense", true);
                    this.EnableMatchBraces = GetBooleanValue(keyLanguage, "MatchBraces", true);
                    this.EnableQuickInfo = GetBooleanValue(keyLanguage, "QuickInfo", true);
                    this.EnableShowMatchingBrace = GetBooleanValue(keyLanguage, "ShowMatchingBrace", true);
                    this.EnableMatchBracesAtCaret = GetBooleanValue(keyLanguage, "MatchBracesAtCaret", true);
                    this.MaxErrorMessages = GetIntegerValue(keyLanguage, "MaxErrorMessages", 10);
                    this.CodeSenseDelay = GetIntegerValue(keyLanguage, "CodeSenseDelay", 1000);
                    this.EnableAsyncCompletion = GetBooleanValue(keyLanguage, "EnableAsyncCompletion", true);
                    this.EnableFormatSelection = GetBooleanValue(keyLanguage, "EnableFormatSelection", false);
                    this.EnableCommenting = GetBooleanValue(keyLanguage, "EnableCommenting", true);
                    this.AutoOutlining = GetBooleanValue(keyLanguage, "AutoOutlining", true);
                    this.MaxRegionTime = GetIntegerValue(keyLanguage, "MaxRegionTime", 2000); // 2 seconds
                    this.braceFlags = (_HighlightMatchingBraceFlags)GetIntegerValue(keyLanguage, "HighlightMatchingBraceFlags", (int)_HighlightMatchingBraceFlags.HMB_USERECTANGLEBRACES);
                }
            }
        }

19 View Source File : StartUpManager.cs
License : MIT License
Project Creator : AlexanderPro

public static void AddToStartup()
        {
            using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
            {
                key.SetValue(replacedemblyUtils.replacedemblyProductName, replacedemblyUtils.replacedemblyLocation);
            }
        }

19 View Source File : dlgSettings.cs
License : MIT License
Project Creator : 86Box

private void ResetSettings()
        {
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
            if (regkey == null)
            {
                Registry.CurrentUser.CreateSubKey(@"SOFTWARE\86Box");
                regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
                regkey.CreateSubKey("Virtual Machines");
            }
            regkey.Close();

            txtCFGdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\86Box VMs\";
            txtEXEdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\86Box\";
            cbxMinimize.Checked = false;
            cbxShowConsole.Checked = true;
            cbxMinimizeTray.Checked = false;
            cbxCloseTray.Checked = false;
            cbxLogging.Checked = false;
            txtLaunchTimeout.Text = "5000";
            txtLogPath.Text = "";
            cbxGrid.Checked = false;
            txtLogPath.Enabled = false;
            btnBrowse3.Enabled = false;

            settingsChanged = CheckForChanges();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x727

public static void RegistryKeyRule(string randomname)
        {
            string regpath = @"Software\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\Microsoft\Windows\UPnP\" + randomname;
            try
            {
                //授予Restore、Backup、TakeOwnership特权
                TokenManipulator.AddPrivilege("SeRestorePrivilege");
                TokenManipulator.AddPrivilege("SeBackupPrivilege");
                TokenManipulator.AddPrivilege("SeTakeOwnershipPrivilege");

                //更改注册表项值的所有者
                RegistryKey subKey = Registry.LocalMachine.OpenSubKey(regpath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
                RegistrySecurity rs = new RegistrySecurity();
                //设置安全性的所有者为Administrators
                rs.SetOwner(new NTAccount("Administrators"));
                //为注册表项设置权限
                subKey.SetAccessControl(rs);

                //更改注册表项值的权限
                RegistryAccessRule rar = new RegistryAccessRule("Administrators", RegistryRights.FullControl, AccessControlType.Allow);
                rs.AddAccessRule(rar);
                subKey.SetAccessControl(rs);
                subKey.Close();

                RegistryKey rk = Registry.LocalMachine.OpenSubKey(regpath, true);
                //设置Index值为0,隐藏计划任务,默认值为1
                rk.SetValue("Index", 0, RegistryValueKind.DWord);
                rk.Close();

                RegeditKeyExist(regpath);

                string rkl = Registry.LocalMachine + "\\" + regpath;
                Console.WriteLine($"[*] RegistryKey location: \n{rkl}");
            }
            finally
            {
                //删除Restore、Backup、TakeOwnership特权
                TokenManipulator.RemovePrivilege("SeRestorePrivilege");
                TokenManipulator.RemovePrivilege("SeBackupPrivilege");
                TokenManipulator.RemovePrivilege("SeTakeOwnershipPrivilege");

                Console.WriteLine("\n[+] Successfully add scheduled task !");
            }
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void CleanSingle(string command)
        {
            string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
            string keyvalue = string.Empty;
            string regcmd = string.Empty;
            if (command.EndsWith("\\1"))
            {
                regcmd = command;
            }
            else
            {
                regcmd = string.Format("{0}\\1", command);
            }
             
            try
            {
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);

                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        if(regkey.GetValue(subKey).ToString() == regcmd)
                        {
                            keyvalue = subKey;
                            regkey.DeleteValue(subKey);
                            Console.WriteLine(regcmd);
                            Console.WriteLine("[+] Cleaned {0} from HKCU:{1}", command, keypath);
                        }
                    }
                    if(keyvalue != string.Empty)
                    {
                        string mruchars = regkey.GetValue("MRUList").ToString();
                        int index = mruchars.IndexOf(keyvalue);
                        mruchars = mruchars.Remove(index, 1);
                        regkey.SetValue("MRUList", mruchars);
                    }
                }
                regkey.Close();
            }
            catch (ArgumentException)
            {
                Console.WriteLine("[-] Error: Selected Registry value does not exist");
            }
        }

19 View Source File : ProxySetting.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static bool UsedProxy()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            if (rk.GetValue("ProxyEnable").ToString() == "1")
            {
                rk.Close();
                return true;
            }
            else
            {
                rk.Close();
                return false;
            }
        }

19 View Source File : ChromiumBrowser.cs
License : MIT License
Project Creator : acandylevey

public void Register(string Hostname, string ManifestPath)
        {
            string targetKeyPath = regHostnameKeyLocation + Hostname;

            RegistryKey regKey = Registry.CurrentUser.OpenSubKey(targetKeyPath, true);

            if (regKey == null)
                regKey = Registry.CurrentUser.CreateSubKey(targetKeyPath);

            regKey.SetValue("", ManifestPath, RegistryValueKind.String);

            regKey.Close();

            Log.LogMessage("Registered host (" + Hostname + ") with browser " + BrowserName);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Alois-xx

private static void RegisterAsEarlyStartedServiceAndAutoLogger()
        {
            ImportAutoLoggerFile();

            string serviceKeyBase = @"SYSTEM\CurrentControlSet\Services";
            string serviceKeyName =  serviceKeyBase + "\\" + ServiceName;
            var key = Registry.LocalMachine.OpenSubKey(serviceKeyName, true);
            if( key == null )
            {
                key = Registry.LocalMachine.OpenSubKey(serviceKeyBase, true);
                key = key.CreateSubKey(ServiceName);
            }

            // start service as early as possible 
            // but we still loose some events since all services are started concurrently after the servicemain was entered
            key.SetValue("Group", "Video", RegistryValueKind.String);
        }

See More Examples