public static void RenameFontName(RegistryKey key, string original, string target, string value) { // TODO: Use transection. key.SetValue(target, value); key.DeleteValue(original); }
private void button6_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show( "スタートアップを解除しますか?\n" + "レジストリから削除します", "スタートアップ解除", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2 ); if (result == DialogResult.OK) { try { Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( @"Software\Microsoft\Windows\CurrentVersion\Run"); regkey.DeleteValue(Application.ProductName); regkey.Close(); } catch (Exception ee) { MessageBox.Show( "以下の例外が発生しました\nException: " + ee.Message + "\nレジストリへのアクセス許可がないか、すでにスタートアップには登録されていない可能性があります。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } }
internal SystemInformation(RegistryKey key) { bool loaded = false; LastStartupDateTime = DateTime.Now; try { if (key.GetValue(KeyInstallation) != null) { InstallationDateTime = DateTime.ParseExact( (string)key.GetValue(KeyInstallation), "O", CultureInfo.InvariantCulture ); string lastReportDate = (string)key.GetValue(KeyLastReport); if (lastReportDate != null) { LastReportDateTime = DateTime.ParseExact( lastReportDate, "O", CultureInfo.InvariantCulture ); } #if CACHE_SYSTEM_INFORMATION OperatingSystem = (string)key.GetValue(KeyOperatingSystem); OperationSystemVersion = (string)key.GetValue(KeyOperationSystemVersion); Cpu = (string)key.GetValue(KeyCpu); CpuInformation = (string)key.GetValue(KeyCpuInformation); #endif loaded = true; } } catch { // If we were unable to load the settings, initialize new settings. } if (!loaded) { Detect(); key.SetValue(KeyInstallation, InstallationDateTime.ToString("O")); if (key.GetValue(KeyLastReport) != null) key.DeleteValue(KeyLastReport); #if CACHE_SYSTEM_INFORMATION key.SetValue(KeyOperatingSystem, OperatingSystem); key.SetValue(KeyOperationSystemVersion, OperationSystemVersion); key.SetValue(KeyCpu, Cpu); key.SetValue(KeyCpuInformation, CpuInformation); #endif } #if !CACHE_SYSTEM_INFORMATION DetectSystemInformation(); #endif }
protected override void OnShown(EventArgs e) { if (Properties.Settings.Default.Enabled == true) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.SetValue("Ham5teakPresence", Application.ExecutablePath); } else if (Properties.Settings.Default.Disabled == true) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("Ham5teakPresence", false); } if (Properties.Settings.Default.dark == true) { button1.TabStop = true; button1.FlatStyle = FlatStyle.Flat; button1.FlatAppearance.BorderSize = 0; button2.TabStop = true; button2.FlatStyle = FlatStyle.Flat; button2.FlatAppearance.BorderSize = 0; button4.TabStop = true; button4.FlatStyle = FlatStyle.Flat; button4.FlatAppearance.BorderSize = 0; button3.TabStop = true; button3.FlatStyle = FlatStyle.Flat; button3.FlatAppearance.BorderSize = 0; ApplyTheme(Color.FromArgb(34, 34, 34), Color.FromArgb(56, 56, 56), Color.FromArgb(242, 240, 219), Color.FromArgb(56, 56, 56)); } else { ApplyTheme(Color.FromArgb(244, 244, 244), Color.FromArgb(225, 225, 225), Color.FromArgb(0, 0, 0), Color.FromArgb(255, 255, 255)); } }
/// <summary> /// 修改程序在注册表中的键值 /// </summary> /// <param name="flag">1:开机启动</param> private void StartUp(string flag) { try { string path = Application.StartupPath; //当前用户 Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (flag.Equals("1")) { if (Rkey == null) { //当前用户 Rkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); } Rkey.SetValue("通知区动态托盘显示", path); } else { if (Rkey != null) { Rkey.DeleteValue("通知区动态托盘显示", false); } } } catch (Exception ex) { } }
public void TestInitialize() { var counter = Interlocked.Increment(ref s_keyCount); _testKeyName += counter.ToString(); _testKeyName2 += counter.ToString(); rk1 = Microsoft.Win32.Registry.CurrentUser; if (rk1.OpenSubKey(_testKeyName2) != null) rk1.DeleteSubKeyTree(_testKeyName2); if (rk1.GetValue(_testKeyName2) != null) rk1.DeleteValue(_testKeyName2, false); if (rk1.GetValue(_testKeyName) != null) rk1.DeleteValue(_testKeyName); if (rk1.OpenSubKey(_testKeyName) != null) rk1.DeleteSubKeyTree(_testKeyName); }
private void AddToAutostart(bool enabled, string name) { string Path = Directory.GetCurrentDirectory(); string yourKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(yourKey); if (enabled) { if (startupKey.GetValue(name) == null) { startupKey.Close(); startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(yourKey, true); // Add startup reg key startupKey.SetValue(name, Path.ToString()); startupKey.Close(); } } else { // remove startup startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(yourKey, true); startupKey.DeleteValue(name, false); startupKey.Close(); } }
private void button_save_Click(object sender, EventArgs e) { if (_settings.Port != numericUpDown_port.Value) { MessageBox.Show("An application restart is required to change the port."); } _settings.ComputerName = textBox_name.Text; _settings.Port = (int)numericUpDown_port.Value; _settings.AuthorizedDevices = checkBox_authdevices.Checked; _settings.Multicast = checkBox_multicast.Checked; _settings.History = checkBox_history.Checked; _settings.KeepHistory = checkBox_keephistory.Checked; _deviceManager.SaveData(); if (checkBox_startup.Checked) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.SetValue("Icy Monitor Server", Application.ExecutablePath.ToString()); } else { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("Icy Monitor Server", false); } DialogResult = DialogResult.OK; Dispose(); }
/*private void UpdateText(string message) * { * resultBox.Text = message; * }*/ private void watchButton_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); Properties.Settings.Default.ServerAddress = this.serverAddress.Text; Properties.Settings.Default.APIKey = this.apiKey.Text; Properties.Settings.Default.WatchLocation = this.watchFolder.Text; Properties.Settings.Default.DeleteOnUpload = (bool)this.removeUploads.IsChecked; Properties.Settings.Default.AutoStart = (bool)this.autoStart.IsChecked; Properties.Settings.Default.RelaunchOnStartup = (bool)this.relaunchOnStartup.IsChecked; Properties.Settings.Default.Save(); if (this.relaunchOnStartup.IsChecked == true) { rkApp.SetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName, System.Reflection.Assembly.GetExecutingAssembly().Location); } else if (rkApp.GetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName) != null) { rkApp.DeleteValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName); } OnChanged(); this.Close(); }
public void TestInitialize() { var counter = Interlocked.Increment(ref s_keyCount); _testKey += counter.ToString(); _rk1 = Microsoft.Win32.Registry.CurrentUser; if (_rk1.OpenSubKey(_testKey) != null) _rk1.DeleteSubKeyTree(_testKey); if (_rk1.GetValue(_testKey) != null) _rk1.DeleteValue(_testKey); //created the test key. if that failed it will cause many of the test scenarios below fail. try { _rk1 = Microsoft.Win32.Registry.CurrentUser; _rk2 = _rk1.CreateSubKey(_testKey); if (_rk2 == null) { Assert.False(true, "ERROR: Could not create test subkey, this will fail a couple of scenarios below."); } else _keyString = _rk2.ToString(); } catch (Exception e) { Assert.False(true, "ERROR: unexpected exception, " + e.ToString()); } }
private void ToggleSwitch_IsCheckedChanged_1(object sender, EventArgs e) { var btn = sender as ToggleSwitch; if (btn.IsChecked == true) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); Assembly curAssembly = Assembly.GetExecutingAssembly(); key.SetValue(curAssembly.GetName().Name, curAssembly.Location); } else { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); Assembly curAssembly = Assembly.GetExecutingAssembly(); if (key.GetValue(curAssembly.GetName().Name) != null) { key.DeleteValue(curAssembly.GetName().Name); } } XMLHelper.SaveObjAsXml(ProgramData.Instance, "StikyNotesData.xml"); }
// - OK - public static void RemoveFromStartup() { using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser .OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { key.DeleteValue("xFirewall", false); } }
public static void SafeDeleteRegistryValue(RegistryKey regKey, String keyName) { // Can't extend Microsoft.Win32.RegistryKey since its sealed, hence has to put this in Utils.cs try { regKey.DeleteValue(keyName); } catch (ArgumentException) { } }
private static void DeleteSetting(string path, string section, string key) { Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(path + "\\" + section, true); if (regKey != null) { regKey.DeleteValue(key, false); } }
internal void CreateComponentValue(RegistryKey componentKey, string name, object value, RegistryValueKind kind) { if (null == componentKey) throw new ArgumentNullException("Unable to find specified registry key."); if (componentKey.GetValue(name, null) != null && componentKey.GetValueKind(name) != kind) componentKey.DeleteValue(name, false); componentKey.SetValue(name, value, kind); }
// Private static methods private static void DeleteItem(Win32.RegistryKey key, string item) { var name = key .GetValueNames() .FirstOrDefault(n => key.GetValue(n, null) as string == item); if (name != null) { key.DeleteValue(name); } }
/// <summary> /// Updates the checked state of the <paramref name="chk"/> if the <paramref name="valueName"/> /// evaluates to true (i.e., '1' (REG_SZ)) for the passed in <paramref name="registryKey"/>. /// However, if <paramref name="inverse"/> is to true, it updates the checkbox state in reverse manner, i.e., /// if the <paramref name="valueName"/> evaluates to true (i.e., 1), checkbox is set to unchecked. /// </summary> /// <param name="chk"></param> /// <param name="registryKey"></param> /// <param name="valueName"></param> /// <param name="inverse"></param> internal static void SetCheckedStateFromString(this CheckBox chk, RegistryKey registryKey, string valueName, bool inverse = false) { try { string val = (string) registryKey.GetValue(valueName); chk.IsChecked = inverse ? Utils.ReversedStringToBool(val) : Utils.StringToBool(val); } catch (InvalidCastException) { registryKey.DeleteValue(valueName, false); chk.IsChecked = false; } }
private void ConditionalSetValue( RegistryKey key, String valueName, String value ) { if (String.IsNullOrEmpty( value )) { key.DeleteValue( valueName, false ); } else { key.SetValue( valueName, value ); } }
private void noToolStripMenuItem1_Click(object sender, EventArgs e) { noToolStripMenuItem1.Checked = true; yesToolStripMenuItem1.Checked = false; Properties.Settings.Default.Enabled = false; Properties.Settings.Default.Disabled = true; Properties.Settings.Default.Save(); Properties.Settings.Default.Reload(); Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("Ham5teakPresence", false); }
private void CheckBox2_CheckedChanged(object sender, EventArgs e) { if (checkBox2.Checked) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("SmartPcGuard", false); } if (chkStartUp.Checked == true) { checkBox2.Checked = false; } }
public void TestInitialize() { var counter = Interlocked.Increment(ref s_keyCount); _testKey += counter.ToString(); _rk1 = Microsoft.Win32.Registry.CurrentUser; if (_rk1.OpenSubKey(_testKey) != null) _rk1.DeleteSubKeyTree(_testKey); if (_rk1.GetValue(_testKey) != null) _rk1.DeleteValue(_testKey); _rk2 = _rk1.CreateSubKey(_testKey); _keyString = _rk2.ToString(); }
/// <summary> /// 修改指定序号的网卡的MAC地址。 /// </summary> /// <param name="pAdapterIndex">网卡序号</param> /// <param name="pMacAddress">网卡MAC地址</param> /// <returns></returns> public static Boolean ModifyMacAddress(Int32 pAdapterIndex, string pMacAddress) { // 网卡序号从0开始 if (pAdapterIndex < 0) { throw new ApplicationException("无效的网卡序号!"); } string strIndex = pAdapterIndex.ToString().PadLeft(4, '0'); strIndex = strIndex.Substring(strIndex.Length - 4); // 网卡格式。长度为12。剔除里面的-或者: if (!String.IsNullOrEmpty(pMacAddress) && pMacAddress.Length > 0) { pMacAddress = pMacAddress.Trim().Replace(":", "").Replace("-", "").Replace(" ", ""); pMacAddress = pMacAddress.ToUpper(); } if (pMacAddress.Length > 0 && pMacAddress.Length != 12) { throw new ApplicationException("无效的MAC地址"); } Reg.RegistryKey regRoot = Reg.Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\" + strIndex, true); Reg.RegistryKey regParams = regRoot.OpenSubKey(@"Ndi\params\NetworkAddress", true); if (regParams != null) { string[] valNames = regRoot.GetValueNames(); //先删除 if (valNames.Contains("NetworkAddress")) { regRoot.DeleteValue("NetworkAddress"); regParams.SetValue("Default", ""); } if (!string.IsNullOrEmpty(pMacAddress) && pMacAddress.Length > 0) { regRoot.SetValue("NetworkAddress", pMacAddress); regParams.SetValue("Default", pMacAddress); } //Console.WriteLine(regRoot.GetValue("InfPath").ToString()); return(true); } else { throw new ApplicationException("没有找到键值:" + regParams.ToString()); } }
/// <summary> /// Updates the checked state of the <paramref name="chk"/> if the <paramref name="valueName"/> /// evaluates to true (i.e., 1 (REG_DWORD or REG_QWORD)) for the passed in <paramref name="registryKey"/>. /// However, if <paramref name="inverse"/> is to true, it updates the checkbox state in reverse manner, i.e., /// if the <paramref name="valueName"/> evaluates to true (i.e., 1), checkbox is set to unchecked. /// </summary> /// <param name="chk"></param> /// <param name="registryKey"></param> /// <param name="valueName"></param> /// <param name="inverse"></param> /// <param name="nullAsTrue"></param> internal static void SetCheckedState(this CheckBox chk, RegistryKey registryKey, string valueName, bool inverse=false, bool nullAsTrue=false) { try { int? val = (int?) registryKey.GetValue(valueName); if (inverse && !val.HasValue && nullAsTrue) { chk.IsChecked = true; return; } chk.IsChecked = inverse ? Utils.ReversedIntToBool(val) : Utils.IntToBool(val); } catch (InvalidCastException) { registryKey.DeleteValue(valueName, false); chk.IsChecked = false; } }
public bool unregisterProgram(string appName) { try { startupKey = Registry.CurrentUser.OpenSubKey(runKey, true); startupKey.DeleteValue(appName, true); } catch (Exception) { return false; } finally { startupKey.Close(); } return true; }
public void StartExeWhenPcStartup(string filename, string filepath, bool isChecked) { if (isChecked) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.SetValue(filename, filepath); //MessageBox.Show("Uygulama Otomatik Başlamaya Ayarlanmıştır !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue(filename, false); //MessageBox.Show("Uygulama Otomatik Başlama İptal Edilmiştir !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } GC.Collect(); GC.WaitForPendingFinalizers(); }
private static bool deleteValue(int Section, string Location, string Value) { key = getKeySection(Section); try { key = key.OpenSubKey(Location,true); key.DeleteValue(Value, false); } catch { return false; } finally { key.Close(); } return true; }
public static bool TryDeleteValue(this MW32.RegistryKey key, string name, bool throwOnMissingValue = true) { if (key == null) { return(false); } try { key.DeleteValue(name, throwOnMissingValue); } catch (Exception ex) { ex.WriteToExcpetionBuffer(); return(false); } return(true); }
public void RemoveUserDSN(string p_strDSN) { m_intError = 0; m_strError = ""; try { m_oCurrentUserRegKey = Registry.CurrentUser.OpenSubKey(ODBC_INI_REG_PATH + "\\ODBC Data Sources", true); m_oCurrentUserRegKey.DeleteValue(p_strDSN); Registry.CurrentUser.DeleteSubKeyTree(ODBC_INI_REG_PATH + "\\" + p_strDSN, false); } catch (Exception err) { m_intError = -1; m_strError = err.Message; } finally { m_oCurrentUserRegKey.Close(); } }
private void toggle_startWindows_CheckedChanged(object sender, EventArgs e) { var Settingslist = JsonConvert.DeserializeObject <ChatLoggerSettings>(File.ReadAllText(Program.SettingsJsonFile)); if (toggle_startWindows.Checked) { Settingslist.startup = true; Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.SetValue("ChatLogger", Program.ExecutablePath + @"\ChatLogger.exe"); } else { Settingslist.startup = false; Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("ChatLogger", false); } File.WriteAllText(Program.SettingsJsonFile, JsonConvert.SerializeObject(Settingslist, Formatting.Indented)); }
/// <summary> /// 开机启动项 /// </summary> /// <param name="Started">是否启动</param> /// <param name="name">启动值的名称</param> /// <param name="path">启动程序的路径 Application.ExecutablePath</param> public static void RunWhenStart(bool Started, string name, string path) { Microsoft.Win32.RegistryKey HKLM = Microsoft.Win32.Registry.LocalMachine; Microsoft.Win32.RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); if (Started == true) { try { Run.SetValue(name, path); HKLM.Close(); } catch { } } else { try { Run.DeleteValue(name); HKLM.Close(); } catch { } } }
public static RegistryError Delete(RegistryKey regKey, string location, string value) { RegistryError rerr = RegistryError.None; try { regKey = regKey.OpenSubKey(location, true); regKey.DeleteValue(value, false); } catch (Exception e) { rerr = RegistryError.Error; Tracer.Error(e); } finally { regKey.Close(); } return rerr; }
/// <summary> /// Delete the Plex Server run keys for both the user that performed /// the installation, and the user associated with the Plex Service. /// </summary> /// <returns> /// True if the registry value has been deleted, false if the value /// could not be deleted. /// </returns> internal bool DeleteRunValue() { try { using (Win32.RegistryKey key = Win32.Registry.CurrentUser.OpenSubKey(RegistryRunKey, true)) { if (key != null) { try { if (key.GetValue(RegistryRunValue) == null) { return(true); } key.DeleteValue(RegistryRunValue); return(key.GetValue(RegistryRunValue) == null); } catch (ArgumentException) { return(true); } catch (Exception ex) when(ex is ObjectDisposedException || ex is IOException || ex is SecurityException || ex is UnauthorizedAccessException) { OnMessageChanged($"The Run key value could not be deleted. Reason: {ex.Message}"); } } } } catch (Exception ex) when(ex is ObjectDisposedException || ex is SecurityException) { OnMessageChanged($"The Run key value could not be deleted. Reason: {ex.Message}"); } return(false); }
public static void AutostartSoftwareWithWindowsRegistryWriter() { try { if (User.Settings.User.AutostartSoftwareWithWindows) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); if ((string)Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true).GetValue("True Mining") != '"' + System.AppDomain.CurrentDomain.BaseDirectory + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe" + '"') { key.SetValue("True Mining", '"' + System.AppDomain.CurrentDomain.BaseDirectory + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe" + '"'); } } else { if (Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true).GetValue("True Mining") != null) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); key.DeleteValue("True Mining"); } } } catch { } }
private void SaveSettings() { // Store control values. Most values are stored using application binding on the control. Properties.Settings.Default.imageFormat = comboBoxImageFormat.SelectedIndex; using (Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { if (checkBoxLaunchAtBoot.Checked) { // If the checkbox was marked, set a value which will make EasyImgur start at boot. registryKey.SetValue("EasyImgur", QuotedApplicationPath); } else { // Delete our value if one is present; second argument supresses exception on missing value registryKey.DeleteValue("EasyImgur", false); } } UpdateRegistry(false); Properties.Settings.Default.Save(); }
public void TestInitialize() { var counter = Interlocked.Increment(ref s_keyCount); _testKeyName2 += counter.ToString(); _rk1 = Microsoft.Win32.Registry.CurrentUser; if (_rk1.OpenSubKey(_testKeyName2) != null) _rk1.DeleteSubKeyTree(_testKeyName2); if (_rk1.GetValue(_testKeyName2) != null) _rk1.DeleteValue(_testKeyName2); _rk2 = _rk1.CreateSubKey(_testKeyName2); Random rand = new Random(10); Byte[] byteArr = new Byte[rand.Next(0, 100)]; rand.NextBytes(byteArr); _objArr = new Object[6]; _objArr[0] = (Int32)(rand.Next(Int32.MinValue, Int32.MaxValue)); _objArr[1] = (Int64)(rand.NextDouble() * Int64.MaxValue); _objArr[2] = (String)"Hello World"; _objArr[3] = (String)"Hello %path5% World"; _objArr[4] = new String[] { "Hello World", "Hello %path% World" }; _objArr[5] = (Byte[])(byteArr); }
public void ApplyAutoStartSetting(bool autoStartChecked) { if (autoStartChecked) { try { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); Assembly curAssembly = Assembly.GetExecutingAssembly(); key.SetValue(curAssembly.GetName().Name, curAssembly.Location); } catch { } } else { try { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); Assembly curAssembly = Assembly.GetExecutingAssembly(); key.DeleteValue(curAssembly.GetName().Name); } catch { } } }
private void ChkStart_Unchecked(object sender, RoutedEventArgs e) { CheckBox box = sender as CheckBox; box.Content = "Off"; if (box.Tag.ToString() == "khoidong") { File.WriteAllText(Paths.khoidong, "false"); try { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("Student Social", false); } catch (Exception) { } } if (box.Tag.ToString() == "thongbao") { khoidong.Visibility = Visibility.Visible; File.WriteAllText(Paths.thongbao, "false"); spnlAmThanh.Visibility = Visibility.Collapsed; } }
public static int Win32DeleteSubKeyValue(RegistryKey hKey, string value) { int iRet = 0; try { hKey.DeleteValue(value, true); } catch (Exception ex) { iRet = -1; Logger.LogException("Win32DeleteSubKeyValue : ", ex); } return iRet; }
//--------- методы класса ---------// public void Save() { if (CanSave) { Microsoft.Win32.RegistryKey TempRegistryKey = this.RegistryKey; //Extended { object valueParam; bool existsParam = ParameterExist("Extended", TempRegistryKey, out valueParam); if (Extended ^ existsParam) { if (existsParam) { TempRegistryKey.DeleteValue("Extended"); } else { TempRegistryKey.SetValue("Extended", "", RegistryValueKind.String); } } } //Position { object valueParam; bool existsParam = ParameterExist("Position", TempRegistryKey, out valueParam); if (existsParam) { valueParam = ((string)valueParam).ToLower(); } if ((position == true ^ (string)valueParam == "top") || (position == null ^ existsParam == false) || (position == false ^ (string)valueParam == "bottom")) { if (position == null) { TempRegistryKey.DeleteValue("Position"); } else { TempRegistryKey.SetValue("Position", position == true ? "Top" : "Bottom", RegistryValueKind.String); } } } //MUIVerb { if (this.muiVerb != null) { this.muiVerb = this.muiVerb.Trim(); } object valueParam; bool existsParam = ParameterExist("MUIVerb", TempRegistryKey, out valueParam); if (!(muiVerb == null && existsParam == false) || !(muiVerb == (string)valueParam)) { if (muiVerb == null) { TempRegistryKey.DeleteValue("MUIVerb"); } else { TempRegistryKey.SetValue("MUIVerb", muiVerb.Trim()); } } } //Command { if ((this.isMenu == true || this.isMenu == null) && command != null) { throw new Exception("This key is 'menu', commands are not allowed."); } if (!(this.isMenu == true || this.isMenu == null)) { if (command == null) { throw new Exception("This key must have a command."); } this.command = this.command.Trim(); string[] subsection = TempRegistryKey.GetSubKeyNames(); if (subsection.Length == 1) { if (subsection[0] == "command") { RegistryKey RKCommand = TempRegistryKey.OpenSubKey("command", true); object valueParam_1; object valueParam_2; bool ByDefault_Param = ParameterExist("", RKCommand, out valueParam_1); bool DelegateExecute_Param = ParameterExist("DelegateExecute", RKCommand, out valueParam_2); if (ByDefault_Param) { if (this.command != (string)valueParam_1) { RKCommand.SetValue("", this.command); } } else if (DelegateExecute_Param) { if (this.command != (string)valueParam_2) { RKCommand.SetValue("DelegateExecute_Param", this.command); } } else { throw new Exception("Сommand not detected."); } } else { throw new Exception("The 'command' subsection was not detected."); } } else if (subsection.Length == 0) { throw new Exception("The 'command' subsection was not detected."); } } } //RegistryName { if (this.registryName.Length == 0) { throw new MyProgramException("Имя в реестре не может быть пустым.", TypeException.NotFatal); } this.registryName = this.registryName.Trim(); Microsoft.Win32.RegistryKey tmpParent = this.ParentRegistryKey; string tmpRKeyName = this.FullNameRegistryKey; //получение имени ключа for (int i = tmpRKeyName.Length - 1; i > 0; i--) { if (tmpRKeyName[i] == '\\') { tmpRKeyName = tmpRKeyName.Substring(i + 1, tmpRKeyName.Length - i - 1); break; } } if (this.registryName != tmpRKeyName) { string[] sub_names = tmpParent.GetSubKeyNames(); if (IsUniqueName(ref sub_names, this.registryName)) { Microsoft.Win32.RegistryKey target = tmpParent.CreateSubKey(this.registryName); CopyRegistryKey(this.RegistryKey, target); tmpParent.DeleteSubKeyTree(tmpRKeyName); this.FullNameRegistryKey = target.Name; } else { throw new Exception("Не уникльное имя."); } } } canSave = false; } }
public void DeleteValue(string valueName, bool throwOnMissingValue) { registryKey.DeleteValue(valueName, throwOnMissingValue); }
/// <summary> /// Static function that clears out the contents of a key /// </summary> /// <param name="key">Key to be cleared</param> public static void ClearKey( RegistryKey key ) { foreach( string name in key.GetValueNames() ) key.DeleteValue( name ); // TODO: This throws under Mono - Restore when bug is fixed //foreach( string name in key.GetSubKeyNames() ) // key.DeleteSubKeyTree( name ); foreach (string name in key.GetSubKeyNames()) { ClearSubKey(key, name); key.DeleteSubKey( name ); } }
void Unregister(Key key, RegistryKey reg) { if (key.values != null) { foreach (string name in key.values.Keys) { reg.DeleteValue(name, false); } } if (key.children != null) { foreach (Key child in key.children.Values) { if (child.Removal == Removal.ForceRemove) { QuietDeleteSubKeyTree(reg, child.Name); } else { using (RegistryKey subKey = reg.OpenSubKey(child.Name, true)) { if (subKey != null) { Unregister(child, subKey); } } } } } }
/// <summary> /// Used to remove a value from the registry /// </summary> /// <param name="mainKey">Windows.Win32.Registry (Halo 2 uses CurrentUser)</param> /// <param name="subKey">The path to the Label</param> /// <param name="valueName">The Value Label name to remove</param> /// <returns></returns> public static bool removeValue(RegistryKey mainKey, string subKey, string valueName) { RegistryKey the_Reg; try { the_Reg = mainKey.CreateSubKey(@subKey); the_Reg.DeleteValue(valueName); the_Reg.Close(); } catch (Exception e) { return false; } return true; }
/// <summary> /// Static function that clears out the contents of a key /// </summary> /// <param name="key">Key to be cleared</param> public static void ClearKey( RegistryKey key ) { foreach( string name in key.GetValueNames() ) key.DeleteValue( name ); foreach( string name in key.GetSubKeyNames() ) key.DeleteSubKeyTree( name ); }
/// <summary> /// /// </summary> public void Save() { storage.Write("SoundOnFriendOnline", SoundOnFriendOnline); storage.Write("SoundOnMessageReceived", SoundOnMessageReceived); storage.Write("AlwaysOnTop", this.AlwaysOnTop); storage.Write("ConnectAllOnStartup", this.ConnectAllOnStartup); storage.Write("HideOfflineContacts", this.HideOfflineContacts); storage.Write("DisplayTaskBar", this.DisplayTaskBar); storage.Write("PromptOnExit", this.PromptOnExit); storage.Write("InternetConnection", (int)this.InternetConnection); storage.Write("ReconnectOnDisconnection", this.ReconnectOnDisconnection); storage.Write("ExitOnX", this.ExitOnX); storage.Write("ProxyUsername", this.ProxyUsername); storage.Write("ProxyPassword", (this.RememberProxyPassword) ? this.ProxyPassword : string.Empty); storage.Write("RememberProxyPassword", this.RememberProxyPassword); storage.Write("UseProxyAuthentication", this.UseProxyAuthentication); storage.Write("ProxyServerHost", this.ProxyServerHost); storage.Write("ProxyServerPort", this.ProxyServerPort); storage.Write("ContactListWidth", this.ContactListSize.Width); storage.Write("ContactListHeight", this.ContactListSize.Height); storage.Write("TimeStampConversations", this.TimeStampConversations); storage.Write("TimeStampFormat", this.TimeStampFormat); storage.Write("ShowEmoticons", this.ShowEmoticons); storage.Write("SendTypingNotifications", this.SendTypingNotifications); System.Drawing.Rectangle screenSize = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea; if (this.ContactListLocation.X > screenSize.Width) { this.ContactListLocation.X = screenSize.Width - this.ContactListSize.Width; } if (this.ContactListLocation.X < 0) { this.ContactListLocation.X = 1; } if (this.ContactListLocation.Y > screenSize.Height) { this.ContactListLocation.Y = screenSize.Height - this.ContactListSize.Height; } if (this.ContactListLocation.Y < 0) { this.ContactListLocation.Y = 1; } storage.Write("ContactListX", this.ContactListLocation.X); storage.Write("ContactListY", this.ContactListLocation.Y); Win32.RegistryKey startupKey = Config.Constants.StartupRegistryRoot.OpenSubKey(Config.Constants.StartupRegistryPath, true); if (this.LoadOnStartup) { startupKey.SetValue("NBM", System.Windows.Forms.Application.ExecutablePath); } else { startupKey.DeleteValue("NBM", false); } startupKey.Close(); storage.Write("FriendOnlineEvent", (int)this.FriendOnlineEvent); storage.Write("FriendMessageEvent", (int)this.FriendMessageEvent); storage.Write("NumTimesToFlashOnMessageReceived", this.NumTimesToFlashOnMessageReceived); storage.Write("PlaySoundOnFriendOnline", this.PlaySoundOnFriendOnline); storage.Write("PlaySoundOnMessageReceived", this.PlaySoundOnMessageReceived); storage.Write("LogType", (int)this.LogType); }
private void buttonSave_Click(object sender, EventArgs e) { // Open Windows startup registry key _windowsRegistryKey = Registry.CurrentUser.OpenSubKey(MainForm.REGISTRY_KEY_WINDOWS_AUTORUN, true); // Open application preferences registry key _preferencesRegistryKey = Registry.CurrentUser.OpenSubKey(MainForm.REGISTRY_KEY_PREFERENCES, true); // Open application server list registry key _serverListRegistryKey = Registry.CurrentUser.OpenSubKey(MainForm.REGISTRY_KEY_SERVER_LIST, true); // Set option values _preferencesRegistryKey.SetValue(MainForm.REGISTRY_VALUE_UI_UPDATE_INTERVAL, numBoxFormUpdateInterval.Value); _preferencesRegistryKey.SetValue(MainForm.REGISTRY_VALUE_UI_MINIMIZE_TO_TRAY, (checkBoxMinimizeToTray.Checked) ? "True" : "False"); _preferencesRegistryKey.SetValue(MainForm.REGISTRY_VALUE_UI_MINIMIZE_DISABLE_NOTIFICATIONS, (checkBoxDisableTrayNotifications.Checked) ? "True" : "False"); _preferencesRegistryKey.SetValue(MainForm.REGISTRY_VALUE_UI_MINIMIZE_AT_START, (checkBoxMinimizeAtStart.Checked) ? "True" : "False"); _preferencesRegistryKey.SetValue(MainForm.REGISTRY_VALUE_UI_CHECK_FOR_UPDATES_AT_START, (checkBoxCheckForUpdates.Checked) ? "True" : "False"); if (checkBoxStartAtLogin.Checked) { _windowsRegistryKey.SetValue(MainForm.REGISTRY_VALUE_WINDOWS_START_AT_LOGIN, "\"" + Application.ExecutablePath.ToString() + "\""); } else if ((string)_windowsRegistryKey.GetValue(MainForm.REGISTRY_VALUE_WINDOWS_START_AT_LOGIN) != null) { _windowsRegistryKey.DeleteValue(MainForm.REGISTRY_VALUE_WINDOWS_START_AT_LOGIN); } // Close Windows startup registry key _windowsRegistryKey.Close(); // Close application preferences registry key _preferencesRegistryKey.Close(); // Close application server list registry key _serverListRegistryKey.Close(); // Set dialog result DialogResult = DialogResult.OK; // Close dialog Close(); }
// // Button Event Handlers // private void buttonSaveServer_Click(object sender, EventArgs e) { if (ValidateConnectionTabControl()) { // Open application server list registry key _serverListRegistryKey = Registry.CurrentUser.OpenSubKey(MainForm.REGISTRY_KEY_SERVER_LIST, true); string connectAtStart = (checkBoxConnectAtStart.Checked) ? "True" : "False"; if (listBoxServers.SelectedIndex >= 0) { foreach (string registryKeyValue in _serverListRegistryKey.GetValueNames()) { string[] server = (string[])_serverListRegistryKey.GetValue(registryKeyValue); if (registryKeyValue == listBoxServers.SelectedIndex.ToString()) { server[MainForm.INDEX_SERVER_USERNAME] = textBoxUsername.Text; server[MainForm.INDEX_SERVER_PASSWORD] = textBoxPassword.Text; server[MainForm.INDEX_SERVER_HOSTNAME] = textBoxHostname.Text; server[MainForm.INDEX_SERVER_PORT] = textBoxPort.Text; server[MainForm.INDEX_SERVER_AUTOCONNECT] = connectAtStart; } else if (checkBoxConnectAtStart.Checked) { server[MainForm.INDEX_SERVER_AUTOCONNECT] = "False"; } _serverListRegistryKey.SetValue(registryKeyValue, server); } } else { ArrayList serverList = new ArrayList(); foreach (string registryKeyValue in _serverListRegistryKey.GetValueNames()) { string[] server = (string[])_serverListRegistryKey.GetValue(registryKeyValue); if (checkBoxConnectAtStart.Checked) { server[MainForm.INDEX_SERVER_AUTOCONNECT] = "False"; } serverList.Add(server); _serverListRegistryKey.DeleteValue(registryKeyValue); } int index; for (index = 0; index < serverList.Count; index++) { _serverListRegistryKey.SetValue(index.ToString(), serverList[index]); } string[] newregistryKeyValue = { textBoxUsername.Text, textBoxPassword.Text, textBoxHostname.Text, textBoxPort.Text, connectAtStart }; _serverListRegistryKey.SetValue(index.ToString(), newregistryKeyValue); } // Open application server list registry key _serverListRegistryKey.Close(); UpdateServerList(); } }
public static void RemoveFromStartUpWindows() { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("Udyat", false); }
static void Main(string[] param) { _param2 = param; if (param != null && param.Length > 0) { _param = param[0]; if (param.Length > 1) { _param_2 = param[1]; } else { _param_2 = ""; } if (_param.ToUpper() == "CLOSE") { System.Diagnostics.Process.GetCurrentProcess().Kill(); } if (_param.ToUpper() == "SETDB") { if (_param2.Length > 1 && _param2[1].Trim().Length > 0) { Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\AMTANGEE\RemoteUrl"); if (regKey != null) { if (_param2[1].Trim() == "0") { try { regKey.SetValue("DefaultDB", "0"); regKey.DeleteValue("DefaultDB"); } catch { } } else { regKey.SetValue("DefaultDB", _param2[1].Trim(), RegistryValueKind.String); } } if (_param2[1].Trim() == "0") { MessageBox.Show("Standard-Datenbank für FileViewer wurde auf Standard-Einstellungen zurückgesetzt!"); } else { MessageBox.Show("Standard-Datenbank für FileViewer wurde auf '" + _param2[1].Trim() + "' gesetzt!"); } } return; } if (_param == "REG_ALL" || _param == "REG_ALL_ADMIN") { try { if (!IsUserAdministrator() && _param != "REG_ALL_ADMIN") { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location; process.StartInfo.Arguments = "REG_ALL_ADMIN"; process.StartInfo.Verb = "runas"; process.Start(); return; } RegisterUrl(); RegisterSendTo(); RegisterEML(); RegisterFileOpen(); RegisterCall(); } catch { } return; } if (_param == "REG_URL" || _param == "REG_URL_ADMIN") { try { if (!IsUserAdministrator() && _param != "REG_URL_ADMIN") { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location; process.StartInfo.Arguments = "REG_URL_ADMIN"; process.StartInfo.Verb = "runas"; process.Start(); return; } RegisterUrl(); } catch { } MessageBox.Show("Registrierung erfolgreich!"); return; } if (_param == "REG_CALL" || _param == "REG_CALL_ADMIN") { try { if (!IsUserAdministrator() && _param != "REG_CALL_ADMIN") { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location; process.StartInfo.Arguments = "REG_CALL_ADMIN"; process.StartInfo.Verb = "runas"; process.Start(); return; } RegisterCall(); } catch { } MessageBox.Show("Registrierung erfolgreich!"); return; } if (_param == "REG_WITHOUT_PARAM_ADMIN") { try { RegisterFileOpen(); } catch { } return; } if (_param == "REG_EML" || _param == "REG_EML_ADMIN") { try { if (!IsUserAdministrator() && _param != "REG_EML_ADMIN") { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location; process.StartInfo.Arguments = "REG_EML_ADMIN"; process.StartInfo.Verb = "runas"; process.Start(); return; } RegisterEML(); } catch (Exception exc) { MessageBox.Show("Fehler beim Registrieren! Fehler: \r\n" + exc.Message); } MessageBox.Show("Registrierung erfolgreich!"); return; } if (_param == "REG_SENDTO") { try { RegisterSendTo(); } catch { } MessageBox.Show("Registrierung erfolgreich!"); return; } try { if (System.IO.File.Exists(_param)) { System.IO.FileInfo fi = new System.IO.FileInfo(_param); bool found = false; switch (fi.Extension.Replace(".", "").ToUpper()) { case "EML": SetAssociation(".eml", "EML_File", System.IO.Path.Combine(AMTANGEE.SDK.Global.AMTANGEEDirectory, "FileViewer.exe"), "OPENEML", "4", "EML-Datei"); found = true; break; case "MSG": SetAssociation(".msg", "MSG_File", System.IO.Path.Combine(AMTANGEE.SDK.Global.AMTANGEEDirectory, "FileViewer.exe"), "OPENMSG", "4", "MSG-Datei"); found = true; break; case "VCF": SetAssociation(".vcf", "VCF_File", System.IO.Path.Combine(AMTANGEE.SDK.Global.AMTANGEEDirectory, "FileViewer.exe"), "OPENVCF", "5", "VCF-Datei"); found = true; break; case "ICS": SetAssociation(".ics", "ICS_File", System.IO.Path.Combine(AMTANGEE.SDK.Global.AMTANGEEDirectory, "FileViewer.exe"), "OPENICS", "6", "ICS-Datei"); found = true; break; case "VCS": SetAssociation(".vcs", "VCS_File", System.IO.Path.Combine(AMTANGEE.SDK.Global.AMTANGEEDirectory, "FileViewer.exe"), "OPENVCS", "6", "VCS-Datei"); found = true; break; } if (found) { System.Diagnostics.Process.Start(_param); return; } } } catch { } } else { if (!IsUserAdministrator()) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = System.Reflection.Assembly.GetEntryAssembly().Location; process.StartInfo.Arguments = "REG_WITHOUT_PARAM_ADMIN"; process.StartInfo.Verb = "runas"; process.Start(); return; } RegisterFileOpen(); return; } SingleInstanceController controller = new SingleInstanceController(); controller.Run(param); }
private void cbPasswordProtection_CheckedChanged(object sender, EventArgs e) { rk = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\", true); rk.CreateSubKey("Detective 007"); rk = rk.OpenSubKey("Detective 007", true); try { if (cbPasswordProtection.Checked) { bChangePassword.Enabled = !string.IsNullOrEmpty(gp.password); gp.ShowPasswordDialog(true, false); gp.ShowDialog(); if (gp.result == DialogResult.OK) { bChangePassword.Enabled = true; if (!string.IsNullOrEmpty(gp.password)) { rk.SetValue("", gp.password); } } else cbPasswordProtection.Checked = false; } else { bChangePassword.Enabled = false; gp.password = null; rk.DeleteValue(""); MessageBox.Show("Password successfully removed", "Detective 007"); } } catch { } }
/// <summary> /// rename registry value [depricated] /// </summary> /// <param name="parent"></param> /// <param name="oldName"></param> /// <param name="newName"></param> static void RenameVal(RegistryKey parent, string oldName, string newName) { try { object val = parent.GetValue(oldName); RegistryValueKind kind = parent.GetValueKind(oldName); parent.SetValue(newName, val, kind); parent.DeleteValue(oldName); } catch { } }
public void Dispose() { _rk1 = Microsoft.Win32.Registry.CurrentUser; if (_rk1.OpenSubKey(_testKeyName) != null) _rk1.DeleteSubKeyTree(_testKeyName); if (_rk1.GetValue(_testKeyName) != null) _rk1.DeleteValue(_testKeyName); }
private void Button1Click(object sender, EventArgs e) { string password = txtPassword.Text; if (chkPasswordProtect.Checked) { if (password.Length < 3) { MessageBox.Show(LocRm.GetString("Validate_Password"), LocRm.GetString("Note")); return; } } string err = ""; if (!Directory.Exists(txtMediaDirectory.Text)) { err += LocRm.GetString("Validate_MediaDirectory") + "\n"; } if (err != "") { MessageBox.Show(err, LocRm.GetString("Error")); return; } if (numJPEGQuality.Value != MainForm.Conf.JPEGQuality) { MainForm.EncoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (int) numJPEGQuality.Value); } MainForm.Conf.Enable_Error_Reporting = chkErrorReporting.Checked; MainForm.Conf.Enable_Update_Check = chkCheckForUpdates.Checked; MainForm.Conf.Enable_Password_Protect = chkPasswordProtect.Checked; MainForm.Conf.Password_Protect_Password = password; string dir = txtMediaDirectory.Text.Trim(); if (!dir.EndsWith("\\")) dir += "\\"; if (MainForm.Conf.MediaDirectory != dir) { MainForm.Conf.MediaDirectory = dir; Directory.CreateDirectory(dir + "audio"); Directory.CreateDirectory(dir + "video"); foreach (objectsCamera cam in MainForm.Cameras) { Directory.CreateDirectory(dir + "video\\" + cam.directory); Directory.CreateDirectory(dir + "video\\" + cam.directory+"\\thumbs"); } foreach (objectsMicrophone mic in MainForm.Microphones) { Directory.CreateDirectory(dir + "audio\\" + mic.directory); } } MainForm.Conf.NoActivityColor = btnNoDetectColor.BackColor.ToRGBString(); MainForm.Conf.TimestampColor = btnTimestampColor.BackColor.ToRGBString(); MainForm.Conf.ActivityColor = btnDetectColor.BackColor.ToRGBString(); MainForm.Conf.TrackingColor = btnColorTracking.BackColor.ToRGBString(); MainForm.Conf.VolumeLevelColor = btnColorVolume.BackColor.ToRGBString(); MainForm.Conf.MainColor = btnColorMain.BackColor.ToRGBString(); MainForm.Conf.AreaColor = btnColorArea.BackColor.ToRGBString(); MainForm.Conf.BackColor = btnColorBack.BackColor.ToRGBString(); MainForm.Conf.BorderHighlightColor = btnBorderHighlight.BackColor.ToRGBString(); MainForm.Conf.BorderDefaultColor = btnBorderDefault.BackColor.ToRGBString(); MainForm.Conf.Enabled_ShowGettingStarted = chkShowGettingStarted.Checked; MainForm.Conf.MaxMediaFolderSizeMB = Convert.ToInt32(txtMaxMediaSize.Value); MainForm.Conf.DeleteFilesOlderThanDays = Convert.ToInt32(txtDaysDelete.Value); MainForm.Conf.Opacity = tbOpacity.Value; MainForm.Conf.Enable_Storage_Management = chkStorage.Checked; MainForm.Conf.YouTubePassword = txtYouTubePassword.Text; MainForm.Conf.YouTubeUsername = txtYouTubeUsername.Text; MainForm.Conf.BalloonTips = chkBalloon.Checked; MainForm.Conf.TrayIconText = txtTrayIcon.Text; MainForm.Conf.IPCameraTimeout = Convert.ToInt32(txtIPCameraTimeout.Value); MainForm.Conf.ServerReceiveTimeout = Convert.ToInt32(txtServerReceiveTimeout.Value); MainForm.Conf.ServerName = txtServerName.Text; MainForm.Conf.AutoSchedule = chkAutoSchedule.Checked; MainForm.Conf.CPUMax = Convert.ToInt32(numMaxCPU.Value); MainForm.Conf.MaxRecordingThreads = (int)numMaxRecordingThreads.Value; MainForm.Conf.CreateAlertWindows = chkAlertWindows.Checked; MainForm.Conf.MaxRedrawRate = (int)numRedraw.Value; MainForm.Conf.Priority = ddlPriority.SelectedIndex + 1; MainForm.Conf.Monitor = chkMonitor.Checked; MainForm.Conf.ScreensaverWakeup = chkInterrupt.Checked; MainForm.Conf.PlaybackMode = ddlPlayback.SelectedIndex; MainForm.Conf.PreviewItems = (int)numMediaPanelItems.Value; MainForm.Conf.BigButtons = chkBigButtons.Checked; MainForm.Conf.DeleteToRecycleBin = chkRecycle.Checked; MainForm.Conf.SpeechRecognition = chkSpeechRecognition.Checked; MainForm.Iconfont = new Font(FontFamily.GenericSansSerif, MainForm.Conf.BigButtons ? 22 : 15, FontStyle.Bold, GraphicsUnit.Pixel); if (ddlTalkMic.Items.Count == 0) MainForm.Conf.TalkMic = ""; else MainForm.Conf.TalkMic = ddlTalkMic.Enabled ? ddlTalkMic.SelectedItem.ToString() : ""; MainForm.Conf.MinimiseOnClose = chkMinimise.Checked; MainForm.Conf.JPEGQuality = (int) numJPEGQuality.Value; MainForm.Conf.IPv6Disabled = !chkEnableIPv6.Checked; MainForm.SetPriority(); var ips = rtbAccessList.Text.Trim().Split(','); var t = ips.Select(ip => ip.Trim()).Where(ip2 => ip2 != "").Aggregate("", (current, ip2) => current + (ip2 + ",")); MainForm.Conf.AllowedIPList = t.Trim(','); LocalServer.AllowedIPs = null; MainForm.Conf.ShowOverlayControls = chkOverlay.Checked; string lang = ((ListItem) ddlLanguage.SelectedItem).Value[0]; if (lang != MainForm.Conf.Language) { ReloadResources = true; LocRm.CurrentSet = null; } MainForm.Conf.Language = lang; if (chkStartup.Checked) { try { _rkApp = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (_rkApp != null) _rkApp.SetValue("iSpy", "\"" + Application.ExecutablePath + "\" -silent", RegistryValueKind.String); } catch (Exception ex) { MessageBox.Show(ex.Message); Log.Error("",ex);//MainForm.LogExceptionToFile(ex); } } else { try { _rkApp = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (_rkApp != null) _rkApp.DeleteValue("iSpy", false); } catch (Exception ex) { MessageBox.Show(ex.Message); Log.Error("",ex);//MainForm.LogExceptionToFile(ex); } } MainForm.Conf.StopSavingOnStorageLimit = chkStopRecording.Checked; if (!MainForm.Conf.StopSavingOnStorageLimit) MainForm.StopRecordingFlag = false; MainForm.ReloadColors(); DialogResult = DialogResult.OK; Close(); }
private void SaveRegistry() { registry = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree); if (auto_start) registry.SetValue("LightSensor", Application.ExecutablePath, RegistryValueKind.String); else if (registry.GetValue("LightSensor") != null) registry.DeleteValue("LightSensor"); registry = Registry.CurrentUser.OpenSubKey("SOFTWARE\\LightSensor", RegistryKeyPermissionCheck.ReadWriteSubTree); if (registry == null) { registry = Registry.CurrentUser.CreateSubKey("SOFTWARE\\LightSensor", RegistryKeyPermissionCheck.ReadWriteSubTree); } registry.SetValue("Interval", sensor.CheckInterval,RegistryValueKind.DWord); registry.SetValue("CurrentWebCam", sensor.CurrentWebCam, RegistryValueKind.DWord); }
// ReSharper disable once CyclomaticComplexity private void SaveConfiguration() { Settings.Default.Language = cbLanguage.Text; Settings.Default.Ip = tbIp.Text; Settings.Default.Username = tbUsername.Text; Settings.Default.Password = tbPassword.Text; Settings.Default.ConnectionTimeout = Convert.ToInt32(cbConnectionTimeout.Text); Settings.Default.ShowInSystemTray = cbShowInTray.Checked; Settings.Default.ShowNowPlayingBalloonTips = cbShowNowPlayingBalloonTip.Checked; Settings.Default.ShowPlayStatusBalloonTips = cbShowPlayStatusBalloonTip.Checked; Settings.Default.ShowInTaskbar = cbShowInTaskbar.Checked; Settings.Default.StartMinimized = cbStartMinimized.Checked; Settings.Default.ShowConnectionInfo = cbShowConnectionStatusBalloonTip.Checked; Settings.Default.ShowConfigurationAtStart = cbShowConfigurationAtStart.Checked; _regRunAtStartup = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (cbRunAtStartup.Checked) { if (_regRunAtStartup != null) _regRunAtStartup.SetValue(_parent.Language.GetString("global/appName"), "\"" + Application.ExecutablePath + "\""); } else if (_regRunAtStartup != null && _regRunAtStartup.GetValue(_parent.Language.GetString("global/appName")) != null) _regRunAtStartup.DeleteValue(_parent.Language.GetString("global/appName")); if (_regRunAtStartup != null) _regRunAtStartup.Close(); if (!Settings.Default.ShowInSystemTray) Settings.Default.ShowInTaskbar = true; Settings.Default.Save(); }
private void SaveGroupTreeView(RegistryKey rkUser) { QTUtility.GroupPathsDic.Clear(); QTUtility.StartUpGroupList.Clear(); QTUtility.dicGroupShortcutKeys.Clear(); QTUtility.dicGroupNamesAndKeys.Clear(); List<PluginKey> list = new List<PluginKey>(); int num = 1; foreach(TreeNode node in tnGroupsRoot.Nodes) { MenuItemArguments tag = (MenuItemArguments)node.Tag; if(tag == MIA_GROUPSEP) { QTUtility.GroupPathsDic["Separator" + num++] = string.Empty; } else if(node.Nodes.Count > 0) { string text = node.Text; if(text.Length > 0) { string str2 = node.Nodes.Cast<TreeNode>() .Select(node2 => node2.Name) .Where(name => name.Length > 0) .StringJoin(";"); if(str2.Length > 0) { string item = text.Replace(";", "_"); QTUtility.GroupPathsDic[item] = str2; if(node.NodeFont == fntStartUpGroup) { QTUtility.StartUpGroupList.Add(item); } if(tag.KeyShortcut != 0) { if(tag.KeyShortcut > 0x100000) { QTUtility.dicGroupShortcutKeys[tag.KeyShortcut] = item; } QTUtility.dicGroupNamesAndKeys[item] = tag.KeyShortcut; list.Add(new PluginKey(item, new int[] { tag.KeyShortcut })); } } } } } rkUser.DeleteSubKey("Groups", false); using(RegistryKey key = rkUser.CreateSubKey("Groups")) { if(key != null) { foreach(string str4 in QTUtility.GroupPathsDic.Keys) { key.SetValue(str4, QTUtility.GroupPathsDic[str4]); } } } rkUser.DeleteValue("ShortcutKeys_Group", false); if(list.Count > 0) { QTUtility2.WriteRegBinary(list.ToArray(), "ShortcutKeys_Group", rkUser); } }
private void Button1Click(object sender, EventArgs e) { string err = ""; foreach (var s in mediaDirectoryEditor1.Directories) { if (!Directory.Exists(s.Entry)) { err += LocRm.GetString("Validate_MediaDirectory") + " ("+s.Entry+")\n"; break; } } if (err != "") { MessageBox.Show(err, LocRm.GetString("Error")); return; } if (numJPEGQuality.Value != MainForm.Conf.JPEGQuality) { MainForm.EncoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (int) numJPEGQuality.Value); } MainForm.Conf.Enable_Error_Reporting = chkErrorReporting.Checked; MainForm.Conf.Enable_Update_Check = chkCheckForUpdates.Checked; MainForm.Conf.Enable_Password_Protect = chkPasswordProtect.Checked; MainForm.Conf.NoActivityColor = btnNoDetectColor.BackColor.ToRGBString(); MainForm.Conf.ActivityColor = btnDetectColor.BackColor.ToRGBString(); MainForm.Conf.TrackingColor = btnColorTracking.BackColor.ToRGBString(); MainForm.Conf.VolumeLevelColor = btnColorVolume.BackColor.ToRGBString(); MainForm.Conf.MainColor = btnColorMain.BackColor.ToRGBString(); MainForm.Conf.AreaColor = btnColorArea.BackColor.ToRGBString(); MainForm.Conf.BackColor = btnColorBack.BackColor.ToRGBString(); MainForm.Conf.BorderHighlightColor = btnBorderHighlight.BackColor.ToRGBString(); MainForm.Conf.BorderDefaultColor = btnBorderDefault.BackColor.ToRGBString(); MainForm.Conf.Enabled_ShowGettingStarted = chkShowGettingStarted.Checked; MainForm.Conf.Opacity = tbOpacity.Value; MainForm.Conf.OpenGrabs = chkOpenGrabs.Checked; MainForm.Conf.BalloonTips = chkBalloon.Checked; MainForm.Conf.TrayIconText = txtTrayIcon.Text; MainForm.Conf.IPCameraTimeout = Convert.ToInt32(txtIPCameraTimeout.Value); MainForm.Conf.ServerReceiveTimeout = Convert.ToInt32(txtServerReceiveTimeout.Value); MainForm.Conf.ServerName = txtServerName.Text; MainForm.Conf.AutoSchedule = chkAutoSchedule.Checked; MainForm.Conf.CPUMax = Convert.ToInt32(numMaxCPU.Value); MainForm.Conf.MaxRecordingThreads = (int)numMaxRecordingThreads.Value; MainForm.Conf.CreateAlertWindows = chkAlertWindows.Checked; MainForm.Conf.MaxRedrawRate = (int)numRedraw.Value; MainForm.Conf.Priority = ddlPriority.SelectedIndex + 1; MainForm.Conf.Monitor = chkMonitor.Checked; MainForm.Conf.ScreensaverWakeup = chkInterrupt.Checked; MainForm.Conf.PlaybackMode = ddlPlayback.SelectedIndex; MainForm.Conf.PreviewItems = (int)numMediaPanelItems.Value; MainForm.Conf.BigButtons = chkBigButtons.Checked; MainForm.Conf.DeleteToRecycleBin = chkRecycle.Checked; MainForm.Conf.SpeechRecognition = chkSpeechRecognition.Checked; MainForm.Conf.AppendLinkText = txtAppendLinkText.Text; MainForm.Conf.StartupForm = ddlStartUpForm.SelectedItem.ToString(); MainForm.Conf.TrayOnMinimise = chkMinimiseToTray.Checked; MainForm.Conf.MJPEGStreamInterval = (int)numMJPEGStreamInterval.Value; MainForm.Conf.AlertOnDisconnect = txtAlertOnDisconnect.Text; MainForm.Conf.AlertOnReconnect = txtAlertOnReconnect.Text; MainForm.Conf.StartupMode = ddlStartupMode.SelectedIndex; MainForm.Conf.EnableGZip = chkGZip.Checked; MainForm.Conf.DisconnectNotificationDelay = (int)numDisconnectNotification.Value; var l = mediaDirectoryEditor1.Directories.ToList(); MainForm.Conf.MediaDirectories = l.ToArray(); var l2 = ftpEditor1.Servers.ToList(); MainForm.Conf.FTPServers = l2.ToArray(); MainForm.Conf.MailAlertSubject = txtAlertSubject.Text; MainForm.Conf.MailAlertBody = txtAlertBody.Text; MainForm.Conf.SMSAlert = txtSMSBody.Text; MainForm.Conf.VLCFileCache = (int)numFileCache.Value; MainForm.Conf.Password_Protect_Startup = chkPasswordProtectOnStart.Checked; SaveSMTPSettings(); MainForm.Conf.Archive = txtArchive.Text.Trim(); if (!String.IsNullOrEmpty(MainForm.Conf.Archive)) { if (!MainForm.Conf.Archive.EndsWith(@"\")) MainForm.Conf.Archive += @"\"; if (!Directory.Exists(MainForm.Conf.Archive)) { MainForm.Conf.Archive = ""; MainForm.LogErrorToFile("Archive directory ignored - couldn't be found on disk"); } } MainForm.Iconfont = new Font(FontFamily.GenericSansSerif, MainForm.Conf.BigButtons ? 22 : 15, FontStyle.Bold, GraphicsUnit.Pixel); MainForm.Conf.TalkMic = ""; if (ddlTalkMic.Enabled) { if (ddlTalkMic.SelectedIndex>0) MainForm.Conf.TalkMic = ddlTalkMic.SelectedItem.ToString(); } MainForm.Conf.MinimiseOnClose = chkMinimise.Checked; MainForm.Conf.JPEGQuality = (int) numJPEGQuality.Value; MainForm.Conf.IPv6Disabled = !chkEnableIPv6.Checked; MainForm.SetPriority(); var ips = rtbAccessList.Text.Trim().Split(','); var t = ips.Select(ip => ip.Trim()).Where(ip2 => ip2 != "").Aggregate("", (current, ip2) => current + (ip2 + ",")); MainForm.Conf.AllowedIPList = t.Trim(','); LocalServer.AllowedIPs = null; var refs = rtbReferrers.Text.Trim().Split(','); var t2 = refs.Select(ip => ip.Trim()).Where(ip2 => ip2 != "").Aggregate("", (current, ip2) => current + (ip2 + ",")); MainForm.Conf.Referers = t2.Trim(','); LocalServer.AllowedReferers = null; MainForm.Conf.ShowOverlayControls = chkOverlay.Checked; string lang = ((ListItem) ddlLanguage.SelectedItem).Value[0]; if (lang != MainForm.Conf.Language) { ReloadResources = true; LocRm.Reset(); } MainForm.Conf.Language = lang; if (chkStartup.Checked) { try { _rkApp = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (_rkApp != null) _rkApp.SetValue("iSpy", "\"" + Application.ExecutablePath + "\" -silent", RegistryValueKind.String); } catch (Exception ex) { MessageBox.Show(ex.Message); MainForm.LogExceptionToFile(ex); } } else { try { _rkApp = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); if (_rkApp != null) _rkApp.DeleteValue("iSpy", false); } catch (Exception ex) { MessageBox.Show(ex.Message); MainForm.LogExceptionToFile(ex); } } //SetStorageOptions(); MainForm.ReloadColors(); if (ddlJoystick.SelectedIndex > 0) { string nameid = _sticks[ddlJoystick.SelectedIndex - 1]; MainForm.Conf.Joystick.id = nameid.Split('|')[1]; MainForm.Conf.Joystick.XAxis = jaxis1.ID; MainForm.Conf.Joystick.InvertXAxis = jaxis1.Invert; MainForm.Conf.Joystick.YAxis = jaxis2.ID; MainForm.Conf.Joystick.InvertYAxis = jaxis2.Invert; MainForm.Conf.Joystick.ZAxis = jaxis3.ID; MainForm.Conf.Joystick.InvertZAxis = jaxis3.Invert; MainForm.Conf.Joystick.Record = jbutton1.ID; MainForm.Conf.Joystick.Snapshot = jbutton2.ID; MainForm.Conf.Joystick.Talk = jbutton3.ID; MainForm.Conf.Joystick.Listen = jbutton4.ID; MainForm.Conf.Joystick.Play = jbutton5.ID; MainForm.Conf.Joystick.Next = jbutton6.ID; MainForm.Conf.Joystick.Previous = jbutton7.ID; MainForm.Conf.Joystick.Stop = jbutton8.ID; MainForm.Conf.Joystick.MaxMin = jbutton9.ID; } else MainForm.Conf.Joystick.id = ""; MainForm.Conf.Logging.Enabled = chkEnableLogging.Checked; MainForm.Conf.Logging.FileSize = (int)numMaxLogSize.Value; MainForm.Conf.Logging.KeepDays = (int)numKeepLogs.Value; DialogResult = DialogResult.OK; Close(); }
private void button1_Click(object sender, EventArgs e) { //Removing the Console from Windows startup Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.DeleteValue("KeyStrockeTracker", false); }
private void AutoStartUpC(object sender, EventArgs e) { rsg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\"); rsg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\", true); rsg.DeleteValue(mainwindow.programname); mainwindow.displaytips("已经取消了哦", 2000); startup.Checked = false; startupc.Checked = true; }