Microsoft.Win32.RegistryKey.SetValue(string, object, Microsoft.Win32.RegistryValueKind)

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

584 Examples 7

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 : 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 : 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 : 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 : MainForm.cs
License : MIT License
Project Creator : aabiryukov

private void button1_Click(object sender, EventArgs e)
        {
            // Save recent settigns
            Registry.CurrentUser.SetValue(RegistyPathTfsName, tfsUriTextBox.Text);
            Registry.CurrentUser.SetValue(RegistyPathTfsFolder, sourceControlFolderTextBox.Text);

            HistoryViewer.ViewHistory(new Uri(tfsUriTextBox.Text), sourceControlFolderTextBox.Text);
        }

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

public void SetOption(ConfigurationOption option, object optionValue)
        {
            _options[option.Key] = optionValue;

            // Write to registry.
            if (optionValue == null)
            {
                // Acutally, null means delete from registry.
                _registryKey.DeleteValue(option.Key, false);
            }
            else if (option.Type == ConfigurationOptionType.Integer && optionValue is int)
            {
                _registryKey.SetValue(option.Key, optionValue, RegistryValueKind.DWord);
            }
            else if (option.Type == ConfigurationOptionType.String)
            {
                _registryKey.SetValue(option.Key, optionValue.ToString(), RegistryValueKind.String);
            }
            else
            {
                throw new ConfigurationStoreException(string.Format("Expected value of type {0} for option key \"{1}\", but received {2} instead", option.Type, option.Key, optionValue.GetType()));
            }
        }

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 : 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 : 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 : 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 : VssUtils.cs
License : MIT License
Project Creator : alexis-

public static bool SetSnapshotLimit(int count)
    {
      count = Math.Min(512, Math.Max(64, count));

      //
      //Create a value with the name MaxShadowCopies and type DWORD. The default data for this value is 64.The minimum is 1.The maximum is 512.

      using (RegistryKey reg = EnsureSubKeyExists(Registry.LocalMachine, MaxShadowCountKeyPath, true))
      {
        if (reg == null)
          return false;

        reg.SetValue(MaxShadowCountKeyName, count, RegistryValueKind.DWord);
      }

      return true;
    }

19 View Source File : AccountService.cs
License : MIT License
Project Creator : aliprogrammer69

public void Set(AuthConfiguration config) {
            if (config == null) {
                throw new System.NullReferenceException("Config must have value");
            }
            CurrentConfig = config;

            RegistryKey authKey = Registry.CurrentUser.CreateSubKey(Consts.AuthConfigRegKey, true);
            authKey.SetValue("auth", Encrypt(config), RegistryValueKind.Binary);
            authKey.Close();
        }

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);
        }

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 : ConfigService.cs
License : Apache License 2.0
Project Creator : AmpScm

void SaveNumberValues(string regKey, string subKey, IDictionary<string, int> values)
        {
            if (string.IsNullOrEmpty(regKey))
                throw new ArgumentNullException("regKey");
            if (string.IsNullOrEmpty(subKey))
                throw new ArgumentNullException("subKey");
            if (values == null)
                throw new ArgumentNullException("values");

            lock (_lock)
            {
                subKey = regKey + "\\" + subKey;
                using (RegistryKey reg = OpenHKCUKey(subKey))
                {
                    if (reg == null)
                        return;
                    foreach (KeyValuePair<string, int> item in values)
                    {
                        if (item.Value <= 0)
                        {
                            reg.DeleteValue(item.Key, false);
                        }
                        else
                        {
                            reg.SetValue(item.Key, item.Value, RegistryValueKind.DWord);
                        }
                    }
                }
            }
        }

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

public void SetWarningBool(AnkhWarningBool ankhWarningBool, bool value)
        {
            using (RegistryKey rk = OpenHKCUKey("Warnings\\Bools"))
            {
                if (rk == null)
                    return;

                if (value)
                    rk.SetValue(ankhWarningBool.ToString(), 1);
                else
                    rk.DeleteValue(ankhWarningBool.ToString());
            }
        }

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

public void MaybeMigrate()
		{
			IAnkhPackage pkg = GetService<IAnkhPackage>();
			IAnkhCommandService cs = GetService<IAnkhCommandService>();

			if (pkg == null || cs == null)
				return;

			using (RegistryKey rkRoot = pkg.UserRegistryRoot)
			using (RegistryKey ankhMigration = rkRoot.CreateSubKey("AnkhSVN-Trigger"))
			{
				int migrateFrom = 0;
				object value = ankhMigration.GetValue(MigrateId, migrateFrom);

				if (value is int)
					migrateFrom = (int)value;
				else
					ankhMigration.DeleteValue(MigrateId, false);

				if (migrateFrom < 0)
					migrateFrom = 0;

				if (migrateFrom >= AnkhId.MigrateVersion)
					return; // Nothing to do

				try
				{
					if (cs.DirectlyExecCommand(AnkhCommand.MigrateSettings).Success)
					{
						ankhMigration.SetValue(MigrateId, AnkhId.MigrateVersion);
					}
				}
				catch
				{ /* NOP: Don't fail here... ever! */}
			}
		}

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

public void SetStrings(string strName, string[] arValue)
        {
            m_Key.SetValue(strName, arValue, RegistryValueKind.MultiString);
        }

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 : MainForm.cs
License : MIT License
Project Creator : Anc813

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MyVisible)
            {
                MyHide();
                e.Cancel = true;

                hotkey = hotkeyTextBox.Hotkey;

                if (hotkey == null)
                {
                    registryKey.DeleteValue(registryKeyName, false);
                }
                else
                {
                    if (!hotkeyBinder.IsHotkeyAlreadyBound(hotkey))
                    {
                        registryKey.SetValue(registryKeyName, hotkey);
                        if (!hotkeyBinder.IsHotkeyAlreadyBound(hotkey)) hotkeyBinder.Bind(hotkey).To(ToggleMicStatus);
                    }
                }

                muteHotkey = muteTextBox.Hotkey;

                if (muteHotkey == null)
                {
                    registryKey.DeleteValue(registryKeyMute, false);
                }
                else
                {
                    if (!hotkeyBinder.IsHotkeyAlreadyBound(muteHotkey))
                    {
                        registryKey.SetValue(registryKeyMute, muteHotkey);
                        if (!hotkeyBinder.IsHotkeyAlreadyBound(muteHotkey)) hotkeyBinder.Bind(muteHotkey).To(MuteMicStatus);
                    }
                }


                unMuteHotkey = unmuteTextBox.Hotkey;

                if (unMuteHotkey == null)
                {
                    registryKey.DeleteValue(registryKeyUnmute, false);
                }
                else
                {
                    if (!hotkeyBinder.IsHotkeyAlreadyBound(unMuteHotkey))
                    {
                        registryKey.SetValue(registryKeyUnmute, unMuteHotkey);
                        if (!hotkeyBinder.IsHotkeyAlreadyBound(unMuteHotkey)) hotkeyBinder.Bind(unMuteHotkey).To(UnMuteMicStatus);
                    }
                }

            }
        }

19 View Source File : MainForm.cs
License : MIT License
Project Creator : Anc813

private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            micSelectorForm = new MicSelectorForm();
            ComboBox comboBox = micSelectorForm.cbMics;
            comboBox.Items.Clear();

            bool registryExists = false;

            ComboboxItem defaulreplacedem = new ComboboxItem();
            defaulreplacedem.Text = DEFAULT_RECORDING_DEVICE;
            defaulreplacedem.deviceId = "";
            comboBox.Items.Add(defaulreplacedem);

            if (selectedDeviceId == "")
            {
                registryExists = true;
                comboBox.SelectedIndex = comboBox.Items.Count - 1;
            }

            foreach (CoreAudioDevice device in AudioController.GetCaptureDevices())
            {
                if (device.State == DeviceState.Active)
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = device.FullName;
                    item.deviceId = device.Id.ToString();
                    comboBox.Items.Add(item);

                    if (item.deviceId == selectedDeviceId)
                    {
                        registryExists = true;
                        comboBox.SelectedIndex = comboBox.Items.Count - 1;
                    }
                }
            }

            if (!registryExists) {
                ComboboxItem item = new ComboboxItem();
                item.Text = "(unavailable) " + registryDeviceName.ToString();
                item.deviceId = selectedDeviceId.ToString();
                comboBox.Items.Add(item);
                comboBox.SelectedIndex = comboBox.Items.Count - 1;
            }
            DialogResult result = micSelectorForm.ShowDialog();
            Console.WriteLine(result);
            ComboboxItem selectedItem = (ComboboxItem)comboBox.SelectedItem;

            registryKey.SetValue(registryDeviceId, selectedItem.deviceId);
            registryKey.SetValue(registryDeviceName, selectedItem.Text);
            selectedDeviceName = selectedItem.Text;
            selectedDeviceId = selectedItem.deviceId;

            micSelectorForm.Dispose();

            UpdateSelectedDevice();
        }

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

public void AppendEnvironmentVariables(StringDictionary variables)
        {
            RegistryKey key = GetServiceLocalMachineKey();
            if (key == null)
            {
                throw new TempException("Key was not found");
            }
            StringDictionary mainVariables = _services.GetEnvironmentVariables();
            StringDictionary mergedVariables = EnvironmentExtensions.MergeVariables(mainVariables, variables);
            string[] convertedVariables = EnvironmentExtensions.ConvertDictionaryToArray(mergedVariables);
            key.SetValue(Constants.WindowsService.ServiceEnvironmentKeyName, convertedVariables);
        }

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

internal void Remove()
        {
            Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.RegistryKey.OpenBaseKey(_parent.RegistryHive, _parent.RegistryView);
            Microsoft.Win32.RegistryKey key = rootKey.OpenSubKey(_parent.Name, true);
            if (key != null)
            {
                key.SetValue(ValueName, string.Empty, Type);
            }
        }

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

internal void Import(VariableCollection variables)
        {
            Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.RegistryKey.OpenBaseKey(_parent.RegistryHive, _parent.RegistryView);
            Microsoft.Win32.RegistryKey key = rootKey.OpenSubKey(_parent.Name, true);
            if (key != null)
            {
                object value = variables.ReplaceVariables(TypedValue, Type);
                key.SetValue(ValueName, value, Type);
            }
        }

19 View Source File : ProjectView.cs
License : MIT License
Project Creator : AndresTraks

private void HandleEvent(WrapperStatus status)
        {
            switch (status)
            {
                case WrapperStatus.ReadingHeaders:
                    Log("Finding input files...\r\n");
                    break;
                case WrapperStatus.ReadingHeadersDone:
                    cppFilesTab.SetData(Project.RootFolder);
                    Application.UserAppDataRegistry.SetValue("SourceFolder", Project.FullSourcePath);
                    Project.ParseAsync();
                    break;
                case WrapperStatus.ParsingHeaders:
                    cppFilesTab.SetData(null);
                    cppClreplacedesTab.SetData(null);
                    Log("Parsing input files...\r\n");
                    break;
                case WrapperStatus.ParsingHeadersDone:
                    cppFilesTab.SetData(Project.RootFolder);
                    cppClreplacedesTab.SetData(Project);
                    csharpFilesTab.SetData(Project.RootFolder);

                    Log("Transforming C++ to C#...\r\n");
                    Project.TransformAsync();
                    break;
                case WrapperStatus.TransformingCppDone:
                    csharpFilesTab.SetData(Project.RootFolderCSharp);
                    csharpClreplacedesTab.SetData(Project);

                    Log("Writing wrapper...\r\n");
                    Project.WriteWrapperAsync();
                    break;
                case WrapperStatus.WritingWrapperDone:
                    Log("Done\r\n");
                    break;
            }
        }

19 View Source File : RegistryService.cs
License : GNU General Public License v3.0
Project Creator : Angelinsky7

private void SetValueToRegistry<T>(String keyName, T newValue, String opensubKey = REGISTRY_SETTINGS) {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(opensubKey, true);
            key.SetValue(keyName, newValue);
        }

19 View Source File : WebBrowserHelper.cs
License : MIT License
Project Creator : anoyetta

public static void SetUseNewestWebBrowser()
        {
            var filename = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
            if (filename.Contains("vhost"))
            {
                filename = filename.Substring(0, filename.IndexOf('.') + 1) + "exe";
            }

            var key1 = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION");
            var key2 = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS");
            key1?.SetValue(filename, 11001, RegistryValueKind.DWord);
            key2?.SetValue(filename, 11001, RegistryValueKind.DWord);
            key1?.Close();
            key2?.Close();
        }

19 View Source File : Config.cs
License : MIT License
Project Creator : anoyetta

public async void SetStartup(
            bool isStartup) =>
            await Task.Run(() =>
            {
                using (var regkey = Registry.CurrentUser.OpenSubKey(
                    @"Software\Microsoft\Windows\CurrentVersion\Run",
                    true))
                {
                    if (isStartup)
                    {
                        regkey.SetValue(
                            replacedembly.GetExecutingreplacedembly().GetProduct(),
                            $"\"{replacedembly.GetExecutingreplacedembly().Location}\"");
                    }
                    else
                    {
                        regkey.DeleteValue(
                            replacedembly.GetExecutingreplacedembly().GetProduct(),
                            false);
                    }
                }
            });

19 View Source File : FileExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private static void replacedociateExtensionWindows(string extension, string formatDescription)
        {
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                string iconPath = Path.Combine(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), "Icons");
                string iconFile;

                if (File.Exists(Path.Combine(iconPath, extension + ".ico")))
                {
                    iconFile = Path.Combine(iconPath, extension + ".ico");
                }
                else
                {
                    iconFile = Path.Combine(iconPath, "tree.ico");
                }

                RegistryKey extensionKey = Registry.ClreplacedesRoot.OpenSubKey("." + extension, true);

                if (extensionKey != null)
                {
                    Registry.ClreplacedesRoot.DeleteSubKeyTree("." + extension);
                }

                extensionKey = Registry.ClreplacedesRoot.CreateSubKey("." + extension);
                extensionKey.SetValue(null, "TreeViewer." + extension, RegistryValueKind.String);

                RegistryKey commandKey = Registry.ClreplacedesRoot.OpenSubKey("TreeViewer." + extension, true);

                if (commandKey != null)
                {
                    Registry.ClreplacedesRoot.DeleteSubKeyTree("TreeViewer." + extension);
                }

                commandKey = Registry.ClreplacedesRoot.CreateSubKey("TreeViewer." + extension);
                commandKey.SetValue(null, formatDescription, RegistryValueKind.String);

                commandKey.CreateSubKey("DefaultIcon").SetValue(null, "\"" + iconFile + "\"");

                RegistryKey shellKey = commandKey.CreateSubKey("shell");
                shellKey.SetValue(null, "Open", RegistryValueKind.String);

                shellKey.CreateSubKey("Open").CreateSubKey("command").SetValue(null, "\"" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + "\" \"%1\"", RegistryValueKind.String);
            }
        }

19 View Source File : Registry.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private static void SetString(this RegistryKey key, string? name, string value)
            => key.SetValue(name, value, RegistryValueKind.String);

19 View Source File : Registry.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private static void AddName(this RegistryKey key, string name)
            => key.SetValue(name, Array.Empty<byte>(), RegistryValueKind.None);

19 View Source File : LocalServer.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

private static void RegisterObjects()
        {
            if (!IsAdministrator)
            {
                ElevateSelf("/register");
                return;
            }
            //
            // If reached here, we're running elevated
            //

            TraceLogger TL = new TraceLogger("RemoteClientServer")
            {
                Enabled = true
            };

            replacedembly replacedy = replacedembly.GetExecutingreplacedembly();
            Attribute attr = Attribute.GetCustomAttribute(replacedy, typeof(replacedemblyreplacedleAttribute));
            string replacedyreplacedle = ((replacedemblyreplacedleAttribute)attr).replacedle;
            attr = Attribute.GetCustomAttribute(replacedy, typeof(replacedemblyDescriptionAttribute));
            string replacedyDescription = ((replacedemblyDescriptionAttribute)attr).Description;

            //
            // Local server's DCOM/AppID information
            //
            try
            {
                //
                // HKCR\APPID\appid
                //
                using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey("APPID\\" + s_appId))
                {
                    key.SetValue(null, replacedyDescription);
                    key.SetValue("AppID", s_appId);
                    key.SetValue("AuthenticationLevel", 1, RegistryValueKind.DWord);
                }
                //
                // HKCR\APPID\exename.ext
                //
                using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(string.Format("APPID\\{0}", Application.ExecutablePath.Substring(Application.ExecutablePath.LastIndexOf('\\') + 1))))
                {
                    key.SetValue("AppID", s_appId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while registering the server:\n" + ex.ToString(),
                        "Remote Local Server", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            finally
            {
            }

            TL.LogMessage("RegisterObjects", "Registering types");

            //
            // For each of the driver replacedemblies
            //
            foreach (Type type in s_ComObjectTypes)
            {
                TL.LogMessage("RegisterObjects", string.Format("Processing type: {0}, is a COM object: {1}", type.FullName, type.IsCOMObject));
                bool bFail = false;
                try
                {
                    //
                    // HKCR\CLSID\clsid
                    //
                    string clsid = Marshal.GenerateGuidForType(type).ToString("B");
                    string progid = Marshal.GenerateProgIdForType(type);
                    //PWGS Generate device type from the Clreplaced name
                    string deviceType = type.Name;

                    using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(string.Format("CLSID\\{0}", clsid)))
                    {
                        key.SetValue(null, progid);						// Could be replacedyreplacedle/Desc??, but .NET components show ProgId here
                        key.SetValue("AppId", s_appId);
                        using (RegistryKey key2 = key.CreateSubKey("Implemented Categories"))
                        {
                            key2.CreateSubKey("{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}");
                        }
                        using (RegistryKey key2 = key.CreateSubKey("ProgId"))
                        {
                            key2.SetValue(null, progid);
                        }
                        key.CreateSubKey("Programmable");
                        using (RegistryKey key2 = key.CreateSubKey("LocalServer32"))
                        {
                            key2.SetValue(null, Application.ExecutablePath);
                        }
                    }

                    //
                    // HKCR\APPID\clsid  For TheSkyX DCOM
                    //
                    using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey("APPID\\" + clsid))
                    {
                        key.SetValue(null, replacedyDescription);
                        key.SetValue("AppID", clsid);
                        key.SetValue("AuthenticationLevel", 1, RegistryValueKind.DWord);
                    }

                    //
                    // HKCR\CLSID\progid
                    //
                    using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(progid))
                    {
                        key.SetValue(null, replacedyreplacedle);
                        using (RegistryKey key2 = key.CreateSubKey("CLSID"))
                        {
                            key2.SetValue(null, clsid);
                        }
                    }
                    //
                    // ASCOM 
                    //
                    replacedy = type.replacedembly;

                    // Pull the display name from the ServedClreplacedName attribute.
                    attr = Attribute.GetCustomAttribute(type, typeof(ServedClreplacedNameAttribute)); //PWGS Changed to search type for attribute rather than replacedembly
                    string chooserName = ((ServedClreplacedNameAttribute)attr).DisplayName ?? "MultiServer";
                    using (var P = new ASCOM.Utilities.Profile())
                    {
                        P.DeviceType = deviceType;
                        P.Register(progid, chooserName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while registering the server:\n" + ex.ToString(), "Remote Local Server", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    bFail = true;
                }
                finally
                {
                }
                if (bFail) break;
            }
        }

19 View Source File : OneClickInstaller.cs
License : MIT License
Project Creator : Assistant

public static void Register(string Protocol, bool Background = false, string Description = null)
        {
            if (IsRegistered(Protocol) == true)
                return;
            try
            {
                if (Utils.IsAdmin)
                {
                    RegistryKey ProtocolKey = Registry.ClreplacedesRoot.OpenSubKey(Protocol, true);
                    if (ProtocolKey == null)
                        ProtocolKey = Registry.ClreplacedesRoot.CreateSubKey(Protocol, true);
                    RegistryKey CommandKey = ProtocolKey.CreateSubKey(@"shell\open\command", true);
                    if (CommandKey == null)
                        CommandKey = Registry.ClreplacedesRoot.CreateSubKey(@"shell\open\command", true);

                    if (ProtocolKey.GetValue("OneClick-Provider", "").ToString() != "Modreplacedistant")
                    {
                        if (Description != null)
                        {
                            ProtocolKey.SetValue("", Description, RegistryValueKind.String);
                        }
                        ProtocolKey.SetValue("URL Protocol", "", RegistryValueKind.String);
                        ProtocolKey.SetValue("OneClick-Provider", "Modreplacedistant", RegistryValueKind.String);
                        CommandKey.SetValue("", $"\"{Utils.ExePath}\" \"--install\" \"%1\"");
                    }

                    Utils.SendNotify(string.Format((string)Application.Current.FindResource("OneClick:ProtocolHandler:Registered"), Protocol));
                }
                else
                {
                    Utils.StartAsAdmin($"\"--register\" \"{Protocol}\" \"{Description}\"");
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            if (Background)
                Application.Current.Shutdown();
            else
                Pages.Options.Instance.UpdateHandlerStatus();
        }

19 View Source File : Component.cs
License : Microsoft Public License
Project Creator : atrenton

internal static void Register(Type t)
        {
            Tracer.WriteTraceMethodLine();
            if (t.FullName == Component.ProgId)
            {
                if (!IsOneNoteInstalled())
                {
                    var errorMessage =
                      "Oops... Can't register component.\r\n" + ONENOTE_APP_NOT_FOUND;
                    Utils.WinHelper.DisplayError(errorMessage);
                    return;
                }
                WritereplacedemblyInfoProperties();
                try
                {
                    Tracer.WriteDebugLine("Creating HKCR subkey: {0}", s_appId_subkey);
                    using (var k = Registry.ClreplacedesRoot.CreateSubKey(s_appId_subkey))
                    {
                        k.SetValue(null, replacedemblyInfo.Description);

                        // Use the default COM Surrogate process (dllhost.exe) to activate the DLL
                        k.SetValue("DllSurrogate", string.Empty);
                    }
                    Tracer.WriteDebugLine("Updating HKCR subkey: {0}", s_clsId_subkey);
                    using (var k = Registry.ClreplacedesRoot.OpenSubKey(s_clsId_subkey, true))
                    {
                        k.SetValue("AppID", s_appId_guid);
                        using (var defaultIcon = k.CreateSubKey("DefaultIcon"))
                        {
                            var path = replacedembly.GetExecutingreplacedembly().Location;
                            var resourceID = 0;
                            defaultIcon.SetValue(null, $"\"{path}\",{resourceID}");
                        }
                    }
                    // Register add-in for all users
                    Tracer.WriteDebugLine("Creating HKLM subkey: {0}", s_addIn_subkey);
                    using (var k = Registry.LocalMachine.CreateSubKey(s_addIn_subkey))
                    {
                        var dword = RegistryValueKind.DWord;
                        k.SetValue("CommandLineSafe", Component.CommandLineSafe, dword);
                        k.SetValue("Description", Component.Description);
                        k.SetValue("FriendlyName", Component.FriendlyName);
                        k.SetValue("LoadBehavior", Component.LoadBehavior, dword);
                    }
                }
                catch (Exception e)
                {
                    Utils.WinHelper.DisplayError("Oops... Can't register component.");
                    Utils.ExceptionHandler.HandleException(e);
                }
            }
        }

19 View Source File : Component.cs
License : Microsoft Public License
Project Creator : atrenton

internal static void Register(Type t)
        {
            Tracer.WriteTraceMethodLine();
            if (t.FullName == Component.ProgId)
            {
                if (!IsOneNoteInstalled())
                {
                    var errorMessage =
                      "Oops... Can't register component.\r\n" + ONENOTE_APP_NOT_FOUND;
                    Utils.WinHelper.DisplayError(errorMessage);
                    return;
                }
                WritereplacedemblyInfoProperties();
                try
                {
                    Tracer.WriteDebugLine("Creating HKCR subkey: {0}", s_appId_subkey);
                    using (var k = Registry.ClreplacedesRoot.CreateSubKey(s_appId_subkey))
                    {
                        k.SetValue(null, replacedemblyInfo.Description);

                        // Use the default COM Surrogate process (dllhost.exe) to activate the DLL
                        k.SetValue("DllSurrogate", string.Empty);
                    }
                    Tracer.WriteDebugLine("Updating HKCR subkey: {0}", s_clsId_subkey);
                    using (var k = Registry.ClreplacedesRoot.OpenSubKey(s_clsId_subkey, true))
                    {
                        k.SetValue("AppID", s_appId_guid);
                        using (var defaultIcon = k.CreateSubKey("DefaultIcon"))
                        {
                            var path = replacedembly.GetExecutingreplacedembly().Location;
                            var resourceID = 0;
                            defaultIcon.SetValue(null, $"\"{path}\",{resourceID}");
                        }
                    }
                    // Register add-in for all users
                    Tracer.WriteDebugLine("Creating HKLM subkey: {0}", s_addIn_subkey);
                    using (var k = Registry.LocalMachine.CreateSubKey(s_addIn_subkey))
                    {
                        var dword = RegistryValueKind.DWord;
                        k.SetValue("CommandLineSafe", Component.CommandLineSafe, dword);
                        k.SetValue("Description", Component.Description);
                        k.SetValue("FriendlyName", Component.FriendlyName);
                        k.SetValue("LoadBehavior", Component.LoadBehavior, dword);
                    }
                }
                catch (Exception e)
                {
                    Utils.WinHelper.DisplayError("Oops... Can't register component.");
                    Utils.ExceptionHandler.HandleException(e);
                }
            }
        }

19 View Source File : RegistryHandler.cs
License : GNU General Public License v3.0
Project Creator : AutoDarkMode

public static void ColorFilterSetup()
        {
            RegistryKey filterType = null;
            try
            {
                filterType = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\ColorFiltering", true);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "error instantiating color filtering key:");
            }
            //on clean installs this registry key doesn't exist, so we need to create it
            if (filterType == null)
            {
                Logger.Warn("color filter key does not exist, creating");
                filterType = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\ColorFiltering", true);
            }
            var currentValue = filterType.GetValue("Active", null);
            if (currentValue == null) filterType.SetValue("Active", 0, RegistryValueKind.DWord);

            var currentType = filterType.GetValue("FilterType", null);
            if (currentType == null) filterType.SetValue("FilterType", 0, RegistryValueKind.DWord); // 0 = gray

            filterType.SetValue("HotkeyEnabled", 1, RegistryValueKind.DWord); //and we activate the hotkey as free bonus :)
            filterType.Dispose();
        }

19 View Source File : IPCAdapterRpcBuffer.cs
License : MIT License
Project Creator : automuteus

private static void RegisterProtocol()
        {
            // Literally code that only works under Windows. This isn't even included with the .NET Core 3 Linux runtime.
            // Consider handling protocol registration outside of this library.
            using (var key = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Clreplacedes\\" + UriScheme))
            {
                // Replace typeof(App) by the clreplaced that contains the Main method or any clreplaced located in the project that produces the exe.
                // or replace typeof(App).replacedembly.Location by anything that gives the full path to the exe
                var applicationLocation = Program.GetExecutablePath();

                key.SetValue("", "URL:" + FriendlyName);
                key.SetValue("URL Protocol", "");

                using (var defaultIcon = key.CreateSubKey("DefaultIcon"))
                {
                    defaultIcon.SetValue("", applicationLocation + ",1");
                }

                using (var commandKey = key.CreateSubKey(@"shell\open\command"))
                {
                    commandKey.SetValue("", "\"" + applicationLocation + "\" \"%1\"");
                }
            }
        }

19 View Source File : IPCAdapterRpcBuffer.cs
License : MIT License
Project Creator : automuteus

private static void RegisterProtocol()
        {
            // Literally code that only works under Windows. This isn't even included with the .NET Core 3 Linux runtime.
            // Consider handling protocol registration outside of this library.
            //#if _WINDOWS
            using (var key = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Clreplacedes\\" + UriScheme))
            {
                // Replace typeof(App) by the clreplaced that contains the Main method or any clreplaced located in the project that produces the exe.
                // or replace typeof(App).replacedembly.Location by anything that gives the full path to the exe
                var applicationLocation = App.GetExecutablePath();

                key.SetValue("", "URL:" + FriendlyName);
                key.SetValue("URL Protocol", "");

                using (var defaultIcon = key.CreateSubKey("DefaultIcon"))
                {
                    defaultIcon.SetValue("", applicationLocation + ",1");
                }

                using (var commandKey = key.CreateSubKey(@"shell\open\command"))
                {
                    commandKey.SetValue("", "\"" + applicationLocation + "\" \"%1\"");
                }
            }
            //#endif
        }

19 View Source File : RegistrationUtility.cs
License : MIT License
Project Creator : avarghesein

internal static void RegisterLocalServer(Type t)
        {
            GuardNullType(t, "t");  // Check the argument

            if (!ValidateActiveXServerAttribute(t)) return;

            try
            {
                // Open the CLSID key of the component.
                using (RegistryKey keyCLSID = Registry.ClreplacedesRoot.OpenSubKey(
                    @"CLSID\" + t.GUID.ToString("B"), /*writable*/true))
                {
                    // Remove the auto-generated InprocServer32 key after registration
                    // (REGASM puts it there but we are going out-of-proc).
                    keyCLSID.DeleteSubKeyTree("InprocServer32");

                    // Create "LocalServer32" under the CLSID key
                    using (RegistryKey subkey = keyCLSID.CreateSubKey("LocalServer32"))
                    {
                        subkey.SetValue("", replacedembly.GetEntryreplacedembly().Location, RegistryValueKind.String);
                    }
                }
            }
            catch (Exception eX)
            {
                System.Windows.Forms.MessageBox.Show(eX.Message);
            }
        }

19 View Source File : RegistryParameterStore.cs
License : Apache License 2.0
Project Creator : awslabs

public void SetParameter(string name, string value)
        {
            RegistryKey regKey = GetKinesisTapRoot();
            regKey.SetValue(name, value, RegistryValueKind.String);
        }

19 View Source File : Login.cs
License : MIT License
Project Creator : b9q

private void btnLogin_Click(object sender, EventArgs e)
        {
            dynamic result = Networking.Login(flex_username_box.Text, flex_preplacedword_box.Text);

            if (result != null)
            {
                if ((string)result.status == "failed")
                {
                    string issue = (string)result.detail;
                    string extra_information = (string)result.extra;
                    switch (issue)
                    {
                        case "connection error":
                        default:
                            unknown_error();
                            return;
                        case "no account":
                        case "wrong preplacedword":
                            MessageBox.Show("Incorrect username or preplacedword.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            flex_preplacedword_box.ResetText();
                            return;
                        case "sub invalid":
                            MessageBox.Show("Your subscription is invalid or expired.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        case "hwid mismatch":
                            MessageBox.Show("Your PC is not authorized.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        case "banned":
                            MessageBox.Show("Your account has been banned.\nReason: " + extra_information, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            security_functions.delete_self();
                            Environment.Exit(1);
                            return;
                        case "server offline":
                            MessageBox.Show($"The server is currently disabled.\nReason: {(string)result.reason}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Environment.Exit(5);
                            break;
                    }
                }
                else if ((string)result.status == "successful" && (string)result.username == flex_username_box.Text && (int)result.time_left > 0)
                {

                    if (c_utility.get_epoch_time() - (double) result.time > 30)
                    {
                        Environment.Exit(0); //prevent replay attacks
                        return;
                    }

                    if (flex_remember_me.Checked)
                    {
                        Properties.Settings.Default.username = flex_username_box.Text;
                        Properties.Settings.Default.preplacedword = flex_preplacedword_box.Text;
                        Properties.Settings.Default.Save();
                    }

                    RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);

                    key.CreateSubKey("VER$ACE");
                    key = key.OpenSubKey("VER$ACE", true);
                    key.SetValue("username", aes.encrypt_string((string)result.username));

                    MessageBox.Show($"Welcome back, {(string)result.username}!\n This build was created on [BUILD]", "VER$ACE", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    saved_info.username = flex_username_box.Text;
                    saved_info.preplacedword = flex_preplacedword_box.Text;

                    keep_open = true;
                    Forms.Main form = new Forms.Main(result);
                    form.Show();
                    Hide();
                }
                else {
                    unknown_error();
                }
            }
            else {
                unknown_error();
            }
        }

19 View Source File : UninstallEntry.cs
License : GNU General Public License v2.0
Project Creator : BlackTasty

public void CreateUninstaller(double estimatedSize)
        {
            try
            {
                try
                {
                    if (Registry.CurrentUser.OpenSubKey(UninstallRegKeyPath) == null)
                        Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }
                catch
                {
                    Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }

                using (RegistryKey parent = Registry.CurrentUser.OpenSubKey(
                             UninstallRegKeyPath, true))
                {
                    if (parent == null)
                    {
                        throw new Exception("Uninstall registry key not found.");
                    }
                    RegistryKey key = null;

                    try
                    {
                        key = parent.OpenSubKey(GlobalValues.AppName, true) ??
                              parent.CreateSubKey(GlobalValues.AppName);

                        if (key == null)
                        {
                            throw new Exception(string.Format("Unable to create uninstaller \"{0}\\{1}\"", UninstallRegKeyPath, GlobalValues.AppName));
                        }

                        replacedembly asm = GetType().replacedembly;
                        Version v = asm.GetName().Version;
                        string exe = GlobalValues.InstallationPath + GlobalValues.AppName + ".exe";

                        key.SetValue("ApplicationVersion", v.ToString());
                        key.SetValue("HelpLink", "https://osu.ppy.sh/forum/t/756318");
                        key.SetValue("DisplayIcon", exe);
                        key.SetValue("DisplayName", GlobalValues.AppName);
                        key.SetValue("DisplayVersion", v.ToString(2));
                        key.SetValue("EstimatedSize", estimatedSize, RegistryValueKind.DWord);
                        key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
                        key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
                        key.SetValue("NoModify", 1, RegistryValueKind.DWord);
                        key.SetValue("Publisher", "BlackTasty");
                        key.SetValue("URLInfoAbout", "");
                        key.SetValue("InstallLocation", GlobalValues.InstallationPath);
                        key.SetValue("UninstallString", GlobalValues.InstallationPath + "uninstall.exe");
                    }
                    finally
                    {
                        if (key != null)
                        {
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "An error occurred writing uninstall information to the registry. " +
                    "The application has been fully installed but can only be uninstalled manually through " +
                    "deleting the files located in " + GlobalValues.InstallationPath + ".",
                    ex);
            }
        }

19 View Source File : Install.xaml.cs
License : GNU General Public License v2.0
Project Creator : BlackTasty

private void RegisterInRegistry()
        {
            if (!setup.CancellationPending)
            {
                logger.WriteLog("Writing to registry...");
                Invoker.InvokeStatus(progress, txt_log, txt_status, "Creating Registry entries...");
                RegistryKey edgeKey = Registry.CurrentUser.OpenSubKey(@"Software\" + GlobalValues.AppName, true);
                if (edgeKey == null)
                {
                    edgeKey = Registry.CurrentUser.CreateSubKey(@"Software\" + GlobalValues.AppName);
                    edgeKey.SetValue("Path", path);
                    edgeKey.SetValue("Name", path + data);
                    edgeKey.SetValue("GUID", GlobalValues.AppName);
                }

                Status = InstallationStatus.REGISTRY_EDITED;
                CheckCancellation();
            }
        }

19 View Source File : RegistryManager.cs
License : MIT License
Project Creator : BlackDragonBE

public static void AddLogonProfileKey(XTUProfile profile)
        {
            ClearLogonProfileKey();
            RegistryKey key = Registry.CurrentUser.OpenSubKey(Shared.RUN_AT_LOGON_PATH, true);
            key.SetValue(Shared.APP_NAME_VALUE, '"' + Application.ExecutablePath + '"' + " " + profile.Name);
        }

19 View Source File : UninstallEntry.cs
License : GNU General Public License v2.0
Project Creator : BlackTasty

public void CreateUninstaller(double estimatedSize)
        {
            try
            {
                try
                {
                    if (Registry.CurrentUser.OpenSubKey(UninstallRegKeyPath) == null)
                        Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }
                catch
                {
                    Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }

                using (RegistryKey parent = Registry.CurrentUser.OpenSubKey(
                             UninstallRegKeyPath, true))
                {
                    if (parent == null)
                    {
                        throw new Exception("Uninstall registry key not found.");
                    }
                    RegistryKey key = null;

                    try
                    {
                        key = parent.OpenSubKey(GlobalValues.AppName, true) ??
                              parent.CreateSubKey(GlobalValues.AppName);

                        if (key == null)
                        {
                            throw new Exception(string.Format("Unable to create uninstaller \"{0}\\{1}\"", UninstallRegKeyPath, GlobalValues.AppName));
                        }

                        replacedembly asm = GetType().replacedembly;
                        Version v = asm.GetName().Version;
                        string exe = GlobalValues.InstallationPath + GlobalValues.AppName + ".exe";

                        key.SetValue("ApplicationVersion", v.ToString());
                        key.SetValue("HelpLink", "https://osu.ppy.sh/forum/t/756318");
                        key.SetValue("DisplayIcon", exe);
                        key.SetValue("DisplayName", GlobalValues.AppName);
                        key.SetValue("DisplayVersion", v.ToString(2));
                        key.SetValue("EstimatedSize", estimatedSize, RegistryValueKind.DWord);
                        key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
                        key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
                        key.SetValue("NoModify", 1, RegistryValueKind.DWord);
                        key.SetValue("Publisher", "BlackTasty");
                        key.SetValue("URLInfoAbout", "");
                        key.SetValue("InstallLocation", GlobalValues.InstallationPath);
                        key.SetValue("UninstallString", GlobalValues.InstallationPath + "uninstall.exe");
                    }
                    finally
                    {
                        if (key != null)
                        {
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "An error occurred writing uninstall information to the registry. The application has been fully installed but can only be uninstalled manually through deleting the files located in " + GlobalValues.InstallationPath + ".",
                    ex);
            }
        }

19 View Source File : UninstallEntry.cs
License : GNU General Public License v2.0
Project Creator : BlackTasty

public void CreateUninstaller(double estimatedSize)
        {
            try
            {
                try
                {
                    if (Registry.CurrentUser.OpenSubKey(UninstallRegKeyPath) == null)
                        Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }
                catch
                {
                    Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }

                using (RegistryKey parent = Registry.CurrentUser.OpenSubKey(
                             UninstallRegKeyPath, true))
                {
                    if (parent == null)
                    {
                        throw new Exception("Uninstall registry key not found.");
                    }
                    RegistryKey key = null;

                    try
                    {
                        key = parent.OpenSubKey(GlobalValues.AppName, true) ??
                              parent.CreateSubKey(GlobalValues.AppName);

                        if (key == null)
                        {
                            throw new Exception(string.Format("Unable to create uninstaller \"{0}\\{1}\"", UninstallRegKeyPath, GlobalValues.AppName));
                        }

                        replacedembly asm = GetType().replacedembly;
                        Version v = asm.GetName().Version;
                        string exe = GlobalValues.InstallationPath + GlobalValues.AppName + ".exe";

                        key.SetValue("ApplicationVersion", v.ToString());
                        key.SetValue("HelpLink", "https://osu.ppy.sh/forum/t/756318");
                        key.SetValue("DisplayIcon", exe);
                        key.SetValue("DisplayName", GlobalValues.AppName);
                        key.SetValue("DisplayVersion", v.ToString(2));
                        key.SetValue("EstimatedSize", estimatedSize, RegistryValueKind.DWord);
                        key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
                        key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
                        key.SetValue("NoModify", 1, RegistryValueKind.DWord);
                        key.SetValue("Publisher", "BlackTasty");
                        key.SetValue("URLInfoAbout", "");
                        key.SetValue("InstallLocation", GlobalValues.InstallationPath);
                        key.SetValue("UninstallString", GlobalValues.InstallationPath + "uninstall.exe");
                    }
                    finally
                    {
                        if (key != null)
                        {
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "An error occurred writing uninstall information to the registry. The application has been fully installed but can only be uninstalled manually through deleting the files located in " + GlobalValues.InstallationPath + ".",
                    ex);
            }
        }

19 View Source File : UninstallEntry.cs
License : GNU General Public License v2.0
Project Creator : BlackTasty

public void CreateUninstaller(double estimatedSize)
        {
            try
            {
                try
                {
                    if (Registry.CurrentUser.OpenSubKey(UninstallRegKeyPath) == null)
                        Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }
                catch
                {
                    Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }

                using (RegistryKey parent = Registry.CurrentUser.OpenSubKey(
                             UninstallRegKeyPath, true))
                {
                    if (parent == null)
                    {
                        throw new Exception("Uninstall registry key not found.");
                    }
                    RegistryKey key = null;

                    try
                    {
                        key = parent.OpenSubKey(GlobalValues.AppName, true) ??
                              parent.CreateSubKey(GlobalValues.AppName);

                        if (key == null)
                        {
                            throw new Exception(string.Format("Unable to create uninstaller \"{0}\\{1}\"", UninstallRegKeyPath, GlobalValues.AppName));
                        }

                        replacedembly asm = GetType().replacedembly;
                        Version v = asm.GetName().Version;
                        string exe = GlobalValues.InstallationPath + GlobalValues.AppName + ".exe";

                        key.SetValue("ApplicationVersion", v.ToString());
                        key.SetValue("HelpLink", "https://osu.ppy.sh/forum/t/756318");
                        key.SetValue("DisplayIcon", exe);
                        key.SetValue("DisplayName", GlobalValues.AppName);
                        key.SetValue("DisplayVersion", v.ToString(2));
                        key.SetValue("EstimatedSize", estimatedSize, RegistryValueKind.DWord);
                        key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
                        key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
                        key.SetValue("NoModify", 1, RegistryValueKind.DWord);
                        key.SetValue("Publisher", "BlackTasty");
                        key.SetValue("URLInfoAbout", "");
                        key.SetValue("InstallLocation", GlobalValues.InstallationPath);
                        key.SetValue("UninstallString", GlobalValues.InstallationPath + "uninstall.exe");
                    }
                    finally
                    {
                        if (key != null)
                        {
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "An error occurred writing uninstall information to the registry. " +
                    "The application has been fully installed but can only be uninstalled manually through " +
                    "deleting the files located in " + GlobalValues.InstallationPath + ".",
                    ex);
            }
        }

19 View Source File : RegistryEx.cs
License : MIT License
Project Creator : BluePointLilac

public static void CopyTo(this RegistryKey srcKey, RegistryKey dstKey)
        {
            foreach(string name in srcKey.GetValueNames())
            {
                dstKey.SetValue(name, srcKey.GetValue(name), srcKey.GetValueKind(name));
            }
            foreach(string name in srcKey.GetSubKeyNames())
            {
                using(RegistryKey srcSubKey = srcKey.OpenSubKey(name))
                using(RegistryKey dstSubKey = dstKey.CreateSubKey(name, true))
                    srcSubKey.CopyTo(dstSubKey);
            }
        }

19 View Source File : ShellNewList.cs
License : MIT License
Project Creator : BluePointLilac

private void AddNewItem()
        {
            NewItem newItem = new NewItem();
            this.AddItem(newItem);
            newItem.AddNewItem += () =>
            {
                using(FileExtensionDialog dlg = new FileExtensionDialog())
                {
                    if(dlg.ShowDialog() != DialogResult.OK) return;
                    string extension = dlg.Extension;
                    if(extension == ".") return;
                    string openMode = FileExtension.GetOpenMode(extension);
                    if(string.IsNullOrEmpty(openMode))
                    {
                        if(AppMessageBox.Show(AppString.Message.NoOpenModeExtension,
                            MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            ExternalProgram.ShowOpenWithDialog(extension);
                        }
                        return;
                    }
                    foreach(Control ctr in this.Controls)
                    {
                        if(ctr is ShellNewItem item)
                        {
                            if(item.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase))
                            {
                                AppMessageBox.Show(AppString.Message.HasBeenAdded);
                                return;
                            }
                        }
                    }

                    using(RegistryKey root = Registry.ClreplacedesRoot)
                    using(RegistryKey exKey = root.OpenSubKey(extension, true))
                    using(RegistryKey snKey = exKey.CreateSubKey("ShellNew", true))
                    {
                        string defaultOpenMode = exKey.GetValue("")?.ToString();
                        if(string.IsNullOrEmpty(defaultOpenMode)) exKey.SetValue("", openMode);

                        byte[] bytes = GetWebShellNewData(extension);
                        if(bytes != null) snKey.SetValue("Data", bytes, RegistryValueKind.Binary);
                        else snKey.SetValue("NullFile", "", RegistryValueKind.String);

                        ShellNewItem item = new ShellNewItem(this, snKey.Name);
                        this.AddItem(item);
                        item.Focus();
                        if(item.ItemText.IsNullOrWhiteSpace())
                        {
                            item.ItemText = FileExtension.GetExtentionInfo(FileExtension.replacedocStr.FriendlyDocName, extension);
                        }
                        if(ShellNewLockItem.IsLocked) this.SaveSorting();
                    }
                }
            };
        }

19 View Source File : EnhanceMenusItem.cs
License : MIT License
Project Creator : BluePointLilac

private static void WriteAttributesValue(XmlNode valueXN, string regPath)
        {
            if(valueXN == null) return;
            if(!XmlDicHelper.FileExists(valueXN)) return;
            if(!XmlDicHelper.JudgeCulture(valueXN)) return;
            if(!XmlDicHelper.JudgeOSVersion(valueXN)) return;
            using(RegistryKey key = RegistryEx.GetRegistryKey(regPath, true, true))
            {
                foreach(XmlNode xn in valueXN.ChildNodes)
                {
                    if(xn is XmlComment) continue;
                    if(!XmlDicHelper.FileExists(xn)) continue;
                    if(!XmlDicHelper.JudgeCulture(xn)) continue;
                    if(!XmlDicHelper.JudgeOSVersion(xn)) continue;
                    foreach(XmlAttribute xa in xn.Attributes)
                    {
                        switch(xn.Name)
                        {
                            case "REG_SZ":
                                key.SetValue(xa.Name, Environment.ExpandEnvironmentVariables(xa.Value), RegistryValueKind.String);
                                break;
                            case "REG_EXPAND_SZ":
                                key.SetValue(xa.Name, xa.Value, RegistryValueKind.ExpandString);
                                break;
                            case "REG_BINARY":
                                key.SetValue(xa.Name, XmlDicHelper.ConvertToBinary(xa.Value), RegistryValueKind.Binary);
                                break;
                            case "REG_DWORD":
                                int num = xa.Value.ToLower().StartsWith("0x") ? 16 : 10;
                                key.SetValue(xa.Name, Convert.ToInt32(xa.Value, num), RegistryValueKind.DWord);
                                break;
                        }
                    }
                }
            }
        }

See More Examples