/// <summary> /// 关联文件 /// </summary> /// <param name="filePathString">应用程序路径</param> /// <param name="pFileTypeName">文件类型</param> public static void SaveReg(string filePathString, string pFileTypeName) { RegistryKey regKey = Registry.ClassesRoot.OpenSubKey("", true); //打开注册表 RegistryKey vrPkey = regKey?.OpenSubKey(pFileTypeName, true); if (vrPkey != null) { regKey.DeleteSubKey(pFileTypeName, true); } regKey?.CreateSubKey(pFileTypeName); vrPkey = regKey?.OpenSubKey(pFileTypeName, true); vrPkey?.SetValue("", "Exec"); vrPkey = regKey?.OpenSubKey("Exec", true); if (vrPkey != null) { regKey.DeleteSubKeyTree("Exec"); //如果等于空就删除注册表DSKJIVR } regKey?.CreateSubKey("Exec"); vrPkey = regKey?.OpenSubKey("Exec", true); vrPkey?.CreateSubKey("shell"); vrPkey = vrPkey?.OpenSubKey("shell", true); //写入必须路径 vrPkey?.CreateSubKey("open"); vrPkey = vrPkey?.OpenSubKey("open", true); vrPkey?.CreateSubKey("command"); vrPkey = vrPkey?.OpenSubKey("command", true); string pathString = "\"" + filePathString + "\" \"%1\""; vrPkey?.SetValue("", pathString); //写入数据 }
private void InstallAdministratorRegistry() { RegistryKey administratorKey = defaultKey?.CreateSubKey("runas", RegistryKeyPermissionCheck.ReadWriteSubTree); try { administratorKey?.SetValue("", runAsAdministratorNameTextBox.Text); } catch { // ignored } try { if (runAsAdministratorIconTextBox.Text != String.Empty) { administratorKey?.SetValue("icon", Path.Combine(IcoDirectory, @"Administrator\Administrator.ico")); } else { administratorKey?.DeleteValue("icon"); } } catch { // ignored } administratorKey?.Close(); }
/// <summary> /// /// </summary> /// <param name="extension"></param> /// <param name="progId"></param> /// <param name="description"></param> /// <param name="icon"></param> /// <param name="application"></param> // Associate file extension with progID, description, icon and application public static void Associate(string extension, string progId, string description, string icon, string application) { RegistryKey registryKey = Registry.ClassesRoot.CreateSubKey(extension); registryKey?.SetValue("", progId); if (string.IsNullOrEmpty(progId)) { return; } using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(progId)) { if (description != null) { key?.SetValue("", description); } if (icon != null) { var subKey = key?.CreateSubKey("DefaultIcon"); subKey?.SetValue("", ToShortPathName(icon)); } if (application != null) { var subKey = key?.CreateSubKey(@"Shell\Open\Command"); subKey?.SetValue("", ToShortPathName(application) + " \"%1\""); } } SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero); }
public void AssociateFiles() { new System.Security.Permissions.RegistryPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert(); try { using (RegistryKey myKey = Registry.ClassesRoot.CreateSubKey(".tga")) { myKey?.SetValue("", "ArdaViewer.tga"); } using (RegistryKey myKey = Registry.ClassesRoot.CreateSubKey("ArdaViewer.tga")) { myKey?.SetValue("", "TGA"); RegistryKey shell = myKey?.CreateSubKey("shell"); shell = shell?.CreateSubKey("open"); shell?.CreateSubKey("command").SetValue("", "\"" + Application.ExecutablePath + "\" \"" + "%1\""); } MessageBox.Show("Restart might be required for changes to take full effect."); } catch { MessageBox.Show("This action requires Registry Write Permission. Try running the application with administrator privileges and try again."); } finally { System.Security.Permissions.RegistryPermission.RevertAssert(); } }
private void InstallLink() { DebugWriteLine("Problem: InstallLink"); MessageBox.Show("Please nagivate to your Leaguesharp folder and select your loader.exe"); OpenFileDialog loaderdialog = new OpenFileDialog { Multiselect = false, AddExtension = true, CheckFileExists = true, CheckPathExists = true, DefaultExt = ".exe", Title = "Please select your Loader.exe" }; loaderdialog.ShowDialog(); string loaderPath = loaderdialog.FileName; DebugWriteLine("Selected loader path " + loaderPath); DebugWriteLine("Deleting old reg key"); string[] subKeys = Registry.ClassesRoot.GetSubKeyNames(); if (subKeys.Contains("ls")) { Registry.ClassesRoot.DeleteSubKeyTree("ls"); } DebugWriteLine("Adding level 0 ls reg key"); //level 0 ls RegistryKey baseKey = Registry.ClassesRoot.CreateSubKey("ls"); baseKey?.SetValue(null, "URL:Custom Protocol", RegistryValueKind.String); baseKey?.SetValue("URL Protocol", ""); DebugWriteLine("Adding level 1 stdIcon reg key"); //level 1 stdIcon RegistryKey stdIcon = baseKey?.CreateSubKey("DefaultIcon"); stdIcon?.SetValue(null, loaderPath + ",0", RegistryValueKind.String); DebugWriteLine("Adding level 1 shell reg key"); //level 1 shell RegistryKey shell = baseKey?.CreateSubKey("shell"); DebugWriteLine("Adding level 2 open reg key"); //level 2 open RegistryKey open = shell?.CreateSubKey("open"); open?.SetValue(null, "\"" + loaderPath + "\" \",%1\"", RegistryValueKind.String); DebugWriteLine("Adding level 3 command reg key"); //level 3 command RegistryKey command = open?.CreateSubKey("command"); command?.SetValue(null, "\"" + loaderPath + "\" \"%1\"", RegistryValueKind.String); DebugWriteLine("InstallLink fix done"); DebugWriteLine("Exitcode 0"); }
/// <summary> /// Asocia una extensión con un ejecutable y una acción /// </summary> public void LinkExtension(string extension, string executableFileName, string programId, string command = "open", string description = "") { string linkedProgramID; RegistryKey registryKey = null; RegistryKey registryKeyShell = null; // El comando predeterminado es open if (string.IsNullOrEmpty(command)) { command = "open"; } // Obtiene la descripción if (string.IsNullOrEmpty(description)) { description = $"{extension} Descripción de {programId}"; } // Normaliza la extensión extension = NormalizeExtension(extension); // Obtiene el ID del programa a partir de la extensión linkedProgramID = GetProgIdFromExtension(extension); // Si no hay nada asociado, se crean las claves, si hay algo asociado se modifican if (string.IsNullOrEmpty(linkedProgramID) || linkedProgramID.Length == 0) { // Crear la clave con la extensión registryKey = Registry.ClassesRoot.CreateSubKey(extension); registryKey?.SetValue("", programId); // Crea la clave con el programa registryKey = Registry.ClassesRoot.CreateSubKey(programId); registryKey?.SetValue("", description); // Crea la clave con el comando registryKeyShell = registryKey?.CreateSubKey($"shell\\{command}\\command"); } else { // Abrimos la clave clave indicando que vamos a escribir para que nos permita crear nuevas subclaves. registryKey = Registry.ClassesRoot.OpenSubKey(linkedProgramID, true); registryKeyShell = registryKey?.OpenSubKey($"shell\\{command}\\command", true); // Si es un comando que se añade, no existirá if (registryKeyShell == null) { registryKeyShell = registryKey?.CreateSubKey(programId); } } // Si tenemos la clave de registro del Shell if (registryKeyShell != null) { registryKeyShell.SetValue("", $"\"{executableFileName}\" \"%1\""); registryKeyShell.Close(); } }
/// <summary> /// Sets the registry key to associat .james files /// </summary> public static void AssociateFileExtension() { if (Config.Instance.FirstInstance) { string executablePath = Config.WorkflowFolderLocation + "\\James.exe"; string iconPath = Config.WorkflowFolderLocation + "\\Resources\\logo2.ico"; RegistryKey FileReg = Registry.CurrentUser.CreateSubKey("Software\\Classes\\.james"); Registry.CurrentUser.CreateSubKey("Software\\Classes\\Applicatons\\MyNotepad.exe"); Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.james"); FileReg?.CreateSubKey("DefaultIcon")?.SetValue("", iconPath); FileReg?.CreateSubKey("shell\\open\\command")?.SetValue("", $"\"{executablePath}\" %1"); } }
public void SaveLastPage(string userName, int page) { RegistryKey masterKey = null; try { masterKey = Registry.CurrentUser.CreateSubKey(MASTER_REG_KEY); RegistryKey userKey = masterKey?.CreateSubKey($"{SAVED_USERS_SUB_KEY}\\{userName}"); if (userKey == null) { return; } userKey.SetValue("LastPage", page); } catch (Exception ex) { Trace.WriteError("Saving user info to registry failed", Trace.GetMethodName(), CLASSNAME, ex); } finally { masterKey?.Close(); } }
internal static void ConfigurateRegistry() { string fileName = Process.GetCurrentProcess().MainModule.ModuleName; string cacheFilePath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)}\Package Cache\{GUID}\{fileName}"; RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", true); var key = registryKey?.CreateSubKey(GUID); if (key != null) { key.SetValue("ApplicationPath", viewModel.InstallFolderPath); key.SetValue("BundleCachePath", $@"{cacheFilePath} "); key.SetValue("BundleProviderKey", GUID); key.SetValue("BundleVersion", "1.0.0.0"); key.SetValue("DisplayIcon", $@"{cacheFilePath} ,0"); key.SetValue("DisplayName", ApplicationName); key.SetValue("DisplayVersion", Settings.Version); key.SetValue("EstimatedSize", EstimatedSize); key.SetValue("Installed", 1); key.SetValue("NoElevateOnModify", 1); key.SetValue("Publisher", Manufacturer); key.SetValue("QuietUninstallString", 1); key.SetValue("UninstallString", $"{cacheFilePath} /uninstall"); key.SetValue("URLInfoAbout", SupportUrl); } }
public RegistryConfiguration() { var app = Assembly.GetExecutingAssembly().GetName().Name; _software = Registry.CurrentUser.OpenSubKey("Software", true); _key = _software?.CreateSubKey(app); }
public static void Create(string key, CpuPriorityLevel priorityLevel) { RegistryKey subKey = WorkingKey.CreateSubKey(key); RegistryKey perfOptions = subKey?.CreateSubKey("PerfOptions"); perfOptions?.SetValue("CpuPriorityClass", priorityLevel, RegistryValueKind.DWord); perfOptions?.Close(); }
public static void WriteExecutionLocation() { RegistryKey key = Registry.LocalMachine.OpenSubKey("Software", true); key?.CreateSubKey("NetworkGameCopier"); key = key?.OpenSubKey("NetworkGameCopier", true); key?.SetValue("InstalledPath", Path.GetFullPath(".")); }
public RegistryKey CreateRegKey(string regKeyName = "") { if (string.IsNullOrEmpty(regKeyName)) { regKeyName = _regKey; } else { regKeyName = $"{this._regKey}\\{regKeyName}"; } // creazione chiave _baseKey?.CreateSubKey(regKeyName ?? "", RegistryKeyPermissionCheck.ReadWriteSubTree)?.Close(); // apertura con permessi per modifica permesssi RegistryKey key = _baseKey?.OpenSubKey( regKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions | RegistryRights.ReadKey | RegistryRights.WriteKey | RegistryRights.FullControl ); // permessi da applicare RegistryRights acl = RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete; // attuale policy if (EnvironmentUtils.IsWin()) { try { RegistrySecurity regSec = key?.GetAccessControl(); // aggiunta policy all'attuale regSec?.AddAccessRule( new RegistryAccessRule( $"{Environment.UserDomainName}\\{Environment.UserName}", acl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow ) ); // definizione proprietario regSec?.SetOwner(new NTAccount($"{Environment.UserDomainName}\\{Environment.UserName}")); // applicazione della policy key?.SetAccessControl(regSec); } catch { // ignore } } return(key); }
/// <summary> /// Defines a new custom url protocol for james /// </summary> public static void RegisterCustomProtocol() { if (Config.Instance.FirstInstance) { string executablePath = Config.WorkflowFolderLocation + "\\James.exe"; RegistryKey reg = Registry.CurrentUser.CreateSubKey("Software\\Classes\\james"); reg?.SetValue("URL PROTOCOL", ""); reg?.CreateSubKey("shell\\open\\command")?.SetValue("", $"\"{executablePath}\" \"%1\""); } }
public void LinkExtension(string extension, string executableFileName, string programId, string command, string description) { string linkedProgramID; RegistryKey registryKey = null; RegistryKey registryKeyShell = null; if (string.IsNullOrEmpty(command)) { command = EngineData.Comando; } if (string.IsNullOrEmpty(description)) { description = $"{extension} Descripción de {programId}"; } if (!extension.StartsWith(".")) { extension = "." + extension; } linkedProgramID = GetProgIdFromExtension(extension); if (string.IsNullOrEmpty(linkedProgramID) || linkedProgramID.Length == 0) { registryKey = Registry.ClassesRoot.CreateSubKey(extension); registryKey?.SetValue(string.Empty, programId); registryKey = Registry.ClassesRoot.CreateSubKey(programId); registryKey?.SetValue(string.Empty, description); registryKeyShell = registryKey?.CreateSubKey($"shell\\{command}\\command"); } else { registryKey = Registry.ClassesRoot.OpenSubKey(linkedProgramID, true); registryKeyShell = registryKey?.OpenSubKey($"shell\\{command}\\command", true); if (registryKeyShell == null) { registryKeyShell = registryKey?.CreateSubKey(programId); } } if (registryKeyShell != null) { registryKeyShell.SetValue(string.Empty, $"\"{executableFileName}\" \"%1\""); registryKeyShell.Close(); } }
public void setValue <T>(RegistryHive hive, string subKey, string valueName, T value, RegistryValueKind kind) where T : struct { RegistryKey basekey = RegistryKey.OpenBaseKey(hive, this.registryView); RegistryKey subkey = basekey?.OpenSubKey(subKey, true); if (subkey == null) { subkey = basekey?.CreateSubKey(subKey, true); } subkey?.SetValue(valueName, value, kind); }
private static void RegisterReloadedProtocol() { // Get the user classes subkey. var classesSubKey = Registry.CurrentUser.OpenSubKey("Software", true)?.OpenSubKey("Classes", true); // Add a Reloaded Key. RegistryKey reloadedProtocolKey = classesSubKey?.CreateSubKey($"{Constants.ReloadedProtocol}"); reloadedProtocolKey?.SetValue("", $"URL:{Constants.ReloadedProtocol}"); reloadedProtocolKey?.SetValue("URL Protocol", ""); reloadedProtocolKey?.CreateSubKey(@"shell\open\command")?.SetValue("", $"\"{Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, ".exe")}\" {Constants.ParameterDownload} %1"); }
/// <summary> /// Registers Reloaded Mod Loader as an URL handler for the reloaded:// protocol, allowing /// those links to be redirected to Reloaded for purposes such as GameBanana's 1 click mod installs. /// </summary> private static void SetupURLHandler() { // Get the user classes subkey. var classesSubKey = Registry.CurrentUser.OpenSubKey("Software", true)?.OpenSubKey("Classes", true); // Add a Reloaded Key. RegistryKey reloadedProtocolKey = classesSubKey?.CreateSubKey($"{Strings.Launcher.ReloadedProtocolName}"); reloadedProtocolKey?.SetValue("", $"URL:{Strings.Launcher.ReloadedProtocolName}"); reloadedProtocolKey?.SetValue("URL Protocol", ""); reloadedProtocolKey?.CreateSubKey(@"shell\open\command")?.SetValue("", $"\"{Assembly.GetExecutingAssembly().Location}\" --download %1"); }
/// <summary> /// Adds registry entries to prevent ListDLL nag screens /// </summary> private static void FixRegistryNagOnListDlls() { try { RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true); key?.CreateSubKey("Sysinternals"); key = key?.OpenSubKey("Sysinternals", true); key?.CreateSubKey("ListDLLs"); key = key?.OpenSubKey("ListDLLs", true); key?.SetValue("EulaAccepted", 1); key?.Close(); } catch (Exception ex) { Logger.Warn("Error trying to create registry keys, this is not critical."); Logger.Warn(ex.Message); } }
public void Register(string exePath, string iconPath) { using (RegistryKey shellKey = Registry.ClassesRoot.OpenSubKey("Directory\\shell", true)) { RegistryKey keyFolder = shellKey?.CreateSubKey(KeyFolderName); if (keyFolder == null) { return; } keyFolder.SetValue("Icon", iconPath); keyFolder.CreateSubKey("command").SetValue("", exePath + " " + FilterDirPathArgName + "=\"%1\""); } }
/// <summary> /// Check if mailpassword exists in registry /// </summary> /// <returns></returns> public bool CheckPasswordExists() { RegistryKey pswd = Registry.CurrentUser.OpenSubKey("Software", true); pswd?.CreateSubKey("Bestellsoftware"); pswd = pswd?.OpenSubKey("Bestellsoftware"); if (pswd?.GetValue("Passwort") == null) { pswd?.Close(); return(false); } pswd.Close(); return(true); }
//Редактирование реестра static void Main(string[] args) { //Совершаем навигацию в нужное место и открываем его для записи. RegistryKey currentUserKey = Registry.CurrentUser; RegistryKey softwareKey = currentUserKey.OpenSubKey("Software", true); RegistryKey testFolderKey = softwareKey?.CreateSubKey("TestFolder"); //Совершаем запись в реестр testFolderKey?.SetValue("TheStringName", "I contain string value"); testFolderKey?.SetValue("TheInt32Name", 1234567890); //REG_DWORD - двойное машинное слово (4 байта) //Тип можно указать явно testFolderKey?.SetValue("AnotherName", 1234567890, RegistryValueKind.String); softwareKey?.Close(); }
private void InstallSystemRegistry() { RegistryKey systemKey = defaultKey?.CreateSubKey("runassystem", RegistryKeyPermissionCheck.ReadWriteSubTree); RegistryKey systemKeyCommand = systemKey?.CreateSubKey("command"); try { systemKey?.SetValue("", runAsSystemNameTextBox.Text); } catch { // ignored } try { if (runAsSystemIconTextBox.Text != String.Empty) { systemKey?.SetValue("icon", Path.Combine(IcoDirectory, @"System\System.ico")); } else { systemKey?.DeleteValue("icon"); } } catch { // ignored } try { systemKeyCommand?.SetValue("", $"C:\\Windows\\{(IntPtr.Size >= 8 ? "PsExec64.exe" : "PsExec.exe")} -d -i -s \"%1\" %*"); } catch { // ignored } systemKey?.Close(); }
private void loadConfig() { rootKey = Microsoft.Win32.Registry.CurrentUser; softwareKey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix"); led_matrix_address = (string)softwareKey.GetValue("ip_address","192.168.0.222"); led_matrix.setAddress(led_matrix_address); winamp.winamp_address = (string)softwareKey.GetValue("winamp_address","localhost"); winamp.winamp_port = (int)softwareKey.GetValue("winamp_port",4800); winamp.winamp_pass = (string)softwareKey.GetValue("winamp_pass","pass"); entry_winamp_address.Text = winamp.winamp_address; entry_winamp_port.Text = winamp.winamp_port.ToString(); entry_winamp_pass.Text = winamp.winamp_pass; entry_mpd.Text = (string)softwareKey.GetValue("mpd_address","localhost"); entry_address.Text = led_matrix_address; led_matrix.scroll_speed = (int)softwareKey.GetValue("scroll_speed",10); hscale_shift_speed.Value = led_matrix.scroll_speed; //entry_static_text.Text = (string)softwareKey.GetValue("static_text") }
/// <summary> /// /// </summary> /// <param name="hklm"></param> /// <param name="key"></param> /// <param name="name"></param> /// <param name="value"></param> public static void SetREGSZRegKey(RegistryKey hklm, string key, string name, string value) { try { using (RegistryKey subkey = hklm.CreateSubKey(key)) { if (subkey != null) { subkey.SetValue(name, value); } } } catch (SecurityException) { Log.Error(@"User does not have sufficient rights to modify registry key HKLM\{0}", key); } catch (UnauthorizedAccessException) { Log.Error(@"User does not have sufficient rights to modify registry key HKLM\{0}", key); } }
public static void RegisterFunction(Type type) { string PATH = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.Replace("\\", "/"); string ASSM = Assembly.GetExecutingAssembly().FullName; int startPos = ASSM.ToLower().IndexOf("version=") + "version=".Length; int len = ASSM.ToLower().IndexOf(",", startPos) - startPos; string VER = ASSM.Substring(startPos, len); string GUID = "{" + type.GUID.ToString().ToUpper() + "}"; string NAME = type.Namespace + "." + type.Name; string BASE = @"Classes\" + NAME; string CLSID = @"Classes\CLSID\" + GUID; // open the key RegistryKey CU = Registry.CurrentUser.OpenSubKey("Software", true); // is this version registred? RegistryKey key = CU.OpenSubKey(CLSID + @"\InprocServer32\" + VER); if (key == null) { // The version of this class currently being registered DOES NOT // exist in the registry - so we will now register it // BASE KEY // HKEY_CURRENT_USER\CLASSES\{NAME} key = CU.CreateSubKey(BASE); key.SetValue("", NAME); // HKEY_CURRENT_USER\CLASSES\{NAME}\CLSID} key = CU.CreateSubKey(BASE + @"\CLSID"); key.SetValue("", GUID); // CLSID // HKEY_CURRENT_USER\CLASSES\CLSID\{GUID} key = CU.CreateSubKey(CLSID); key.SetValue("", NAME); // HKEY_CURRENT_USER\CLASSES\CLSID\{GUID}\Implemented Categories key = CU.CreateSubKey(CLSID + @"\Implemented Categories").CreateSubKey("{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}"); // HKEY_CURRENT_USER\CLASSES\CLSID\{GUID}\InProcServer32 key = CU.CreateSubKey(CLSID + @"\InprocServer32"); key.SetValue("", @"c:\Windows\SysWow64\mscoree.dll"); key.SetValue("ThreadingModel", "Both"); key.SetValue("Class", NAME); key.SetValue("CodeBase", PATH); key.SetValue("Assembly", ASSM); key.SetValue("RuntimeVersion", "v4.0.30319"); // HKEY_CURRENT_USER\CLASSES\CLSID\{GUID}\InProcServer32\{VERSION} key = CU.CreateSubKey(CLSID + @"\InprocServer32\" + VER); key.SetValue("Class", NAME); key.SetValue("CodeBase", PATH); key.SetValue("Assembly", ASSM); key.SetValue("RuntimeVersion", "v4.0.30319"); // HKEY_CURRENT_USER\CLASSES\CLSID\{GUID}\ProgId key = CU.CreateSubKey(CLSID + @"\ProgId"); key.SetValue("", NAME); // HKEY_CURRENT_USER\CLASSES\CLSID\{GUID}\Progammable key = CU.CreateSubKey(CLSID + @"\Programmable"); // now register the addin in the addins sub keys for each version of Office foreach (string keyName in Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\").GetSubKeyNames()) { if (IsVersionNum(keyName)) { // if the adding i found in the Add-in Manager - remove it key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\" + keyName + @"\Excel\Add-in Manager", true); if (key != null) { key.SetValue(NAME, ""); } } } if (!fVstoRegister) { // all done - this just helps to assure REGASM is complete // this is not needed, but is useful for troubleshooting MessageBox.Show("Registered " + NAME + "."); } } }
private void load_config() { int i; rootKey = Microsoft.Win32.Registry.CurrentUser; softwareKey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix\lines"); i=0; foreach(string key in softwareKey.GetSubKeyNames()) { string name,code,rss; bool active,loop; int num, time; RegistryKey tempkey; tempkey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix\lines\"+key); num = (int)tempkey.GetValue("num",0); time = (int)tempkey.GetValue("time",0); loop = (string)tempkey.GetValue("loop","True") == "True"; name = (string)tempkey.GetValue("name",""); code = (string)tempkey.GetValue("code",""); rss = (string)tempkey.GetValue("rss",""); active = (string)tempkey.GetValue("active","True") == "True"; user_lines.Add(new userLine(name,active,code,rss,num,loop,time)); Console.WriteLine(key); i++; } if(i==0) { user_lines.Add(new userLine("Spiegel.de",false,"%c%r%8%h:%m:%s%n%g%-%R" ,"http://www.spiegel.de/index.rss",i++,true,10)); user_lines.Add(new userLine("kicker.de",false,"%c%r%8%h:%m:%s%n%g%-%R" ,"http://rss.kicker.de/live/bundesliga",i++,true,10)); user_lines.Add(new userLine("Uhrzeit",true,"%2%+%+%c%r%h:%m:%s" ,"",i++,true,10)); user_lines.Add(new userLine("Wetter",false,"%c%r%8%h:%m:%s%n%g%-%R" ,"http://wetter.bjoern-b.de/daten.xml",i++,true,10)); user_lines.Add(new userLine("Musik+Uhr",false,"%c%r%h:%m:%s%n%-%g%a %o- %g%t" ,"http://wetter.bjoern-b.de/daten.xml",i++,true,10)); user_lines.Add(new userLine("Musik",false,"%r%a %o- %g%t" ,"http://wetter.bjoern-b.de/daten.xml",i++,true,10)); user_lines.Add(new userLine("Weihnachten",false,"%+%+%g%2%T%1%c%+%-%-%-%-%rFrohe%2 %g%+%+%+%T%n%r%1%c%-%-%-%-Weihnachten" ,"",i++,false,10)); } user_lines.Sort(); }
public static void RegisterControl(Type t, int iconResourceIndex = 101) { try { if (t == null) { throw new ArgumentNullException(nameof(t)); } if (!typeof(Control).IsAssignableFrom(t)) { throw new ArgumentException("Type argument must be a Windows Forms control."); } string key = $"CLSID\\{t.GUID:B}"; using (RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(key, true)) { // InprocServer32 using (RegistryKey inprocServerKey = registryKey?.OpenSubKey("InprocServer32", true)) { //Override the default value - to make sure that the applications will be able to locate the DLL inprocServerKey?.SetValue(null, $@"{Environment.SystemDirectory}\mscoree.dll"); // Create the CodeBase entry - needed if not string named and GACced. inprocServerKey?.SetValue("CodeBase", t.Assembly.CodeBase); } // Control // Create the 'Control' key - this allows our control to show up in // the ActiveX control container RegistryKey controlKey = registryKey?.CreateSubKey("Control"); controlKey?.Close(); // MiscStatus using (RegistryKey miscKey = registryKey?.CreateSubKey("MiscStatus")) { const int miscStatusValue = OLEMISC_RECOMPOSEONRESIZE + OLEMISC_CANTLINKINSIDE + OLEMISC_INSIDEOUT + OLEMISC_ACTIVATEWHENVISIBLE + OLEMISC_SETCLIENTSITEFIRST; miscKey?.SetValue("", miscStatusValue.ToString(), RegistryValueKind.String); } // ToolBoxBitmap32 using (RegistryKey bitmapKey = registryKey?.CreateSubKey("ToolboxBitmap32")) { bitmapKey?.SetValue("", $"{t.Assembly.Location}, {iconResourceIndex}", RegistryValueKind.String); } // TypeLib using (RegistryKey typeLibKey = registryKey?.CreateSubKey("TypeLib")) { Guid libId = Marshal.GetTypeLibGuidForAssembly(t.Assembly); typeLibKey?.SetValue("", libId.ToString("B"), RegistryValueKind.String); } // Version using (RegistryKey versionKey = registryKey?.CreateSubKey("Version")) { int major, minor; Marshal.GetTypeLibVersionForAssembly(t.Assembly, out major, out minor); versionKey?.SetValue("", $"{major}.{minor}"); } } EventLogWrapper.Log($"Control registered for {Bitness} applications: {t.FullName}, {key}", EventLogEntryType.Information, 200); } catch (Exception ex) { EventLogWrapper.Log($"Control was not registered: {t.FullName}\n{ex}", EventLogEntryType.Error, 500); } }
public static void RegisterClass(string keyName) { using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(keyName.Replace(@"HKEY_CLASSES_ROOT\", ""), true)) key?.CreateSubKey("Control")?.Close(); }
public static bool Add(string extension, string progId, string description, string executable, bool urlHandler = false) { try { if (!string.IsNullOrEmpty(extension)) { if (extension[0] != '.') { extension = "." + extension; } // register the extension, if necessary using (RegistryKey key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension, true)) { if (key == null) { using (RegistryKey extKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension)) { extKey?.SetValue(string.Empty, progId); } } else { key.SetValue(string.Empty, progId); } } } // register the progId, if necessary using (RegistryKey key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(progId)) { if (key == null || key.OpenSubKey("shell\\open\\command")?.GetValue(string.Empty).ToString() != $"\"{executable}\" \"%1\"") { using (RegistryKey progIdKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(progId)) { if (progIdKey != null) { progIdKey.SetValue(string.Empty, description); if (urlHandler) { progIdKey.SetValue("URL Protocol", string.Empty); } using (RegistryKey command = progIdKey.CreateSubKey("shell\\open\\command")) { command?.SetValue(string.Empty, $"\"{executable}\" \"%1\""); } using (RegistryKey command = progIdKey.CreateSubKey("DefaultIcon")) { command?.SetValue(string.Empty, $"\"{executable}\",1"); } } } } // Add new icon for existing osu! users anyway else if (key.OpenSubKey("DefaultIcon")?.GetValue(string.Empty) == null) { using (RegistryKey progIdKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(progId)) { using (RegistryKey command = progIdKey?.CreateSubKey("DefaultIcon")) { command?.SetValue(string.Empty, $"\"{executable}\",1"); } } } } } catch { return(false); } return(true); }
private bool treemode_foreach_func(Gtk.TreeModel model, Gtk.TreePath path, Gtk.TreeIter iter) { rootKey = Microsoft.Win32.Registry.CurrentUser; softwareKey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix\lines"); userLine line = (userLine)model.GetValue(iter,0); softwareKey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix\lines\"+line.m_name); softwareKey.SetValue("name",line.m_name); softwareKey.SetValue("code",line.m_code); softwareKey.SetValue("active",line.m_active); softwareKey.SetValue("rss",line.m_rss_url); softwareKey.SetValue("loop",line.m_loop); softwareKey.SetValue("time",line.m_time); softwareKey.SetValue("num",line.m_number); return false; // run loop further }
public void Install() { Console.WriteLine("Starting installation"); Console.WriteLine($"Installing: {Info.CurrentInstallingModVersion.Name}"); Console.WriteLine($"To: {Info.CurrentGamePath}"); OnStart?.Invoke(); try { if (Info.CurrentInstalledModVersion != null) { _Restore(); Console.WriteLine(); } _Backup(); Console.WriteLine(); _DownloadAndUnpack(); Console.WriteLine(); // Sneaky step: Copy the installer. string installerPath = null; try { string installerTmpPath = Assembly.GetEntryAssembly().Location; installerPath = Path.Combine(Info.CurrentGamePath, Path.GetFileName(installerTmpPath)); File.Copy(installerTmpPath, installerPath, true); } catch { } // Sneaky step: Set up URI handler. if (!string.IsNullOrEmpty(Info.ModURIProtocol) && !string.IsNullOrEmpty(Info.ModsDir)) { try { RegistryKey regClasses = Registry .CurrentUser ?.OpenSubKey("Software", true) ?.OpenSubKey("Classes", true); RegistryKey regProtocol = regClasses?.CreateSubKey(Info.ModURIProtocol); if (regProtocol != null) { regProtocol.SetValue("", $"URL:{Info.ModURIProtocol}"); regProtocol.SetValue("URL Protocol", ""); regProtocol.CreateSubKey(@"shell\open\command").SetValue("", $"\"{installerPath}\" %1"); } } catch { } } _Install(); Console.WriteLine(); } catch (Exception e) { Console.WriteLine($"Failed installing {Info.CurrentInstallingModVersion.Name}"); Console.WriteLine(e); Console.WriteLine("Error! Please check installer-log.txt"); OnError?.Invoke(e); if (Debugger.IsAttached) { throw; } return; } Console.WriteLine("Finished installing!"); Console.WriteLine(); OnFinish?.Invoke(); }
public static void SaveSettings() { try { PlatformID ptId = DetectOS.GetRealPlatformID(); switch (ptId) { case PlatformID.MacOSX: case PlatformID.iOS: { var root = new NSDictionary { { "TemporaryFolder", Current.TemporaryFolder }, { "DatabasePath", Current.DatabasePath }, { "RepositoryPath", Current.RepositoryPath }, { "UnArchiverPath", Current.UnArchiverPath }, { "CompressionAlgorithm", Current.CompressionAlgorithm.ToString() }, { "UseAntivirus", Current.UseAntivirus }, { "UseClamd", Current.UseClamd }, { "ClamdHost", Current.ClamdHost }, { "ClamdPort", Current.ClamdPort }, { "ClamdIsLocal", Current.ClamdIsLocal }, { "UseVirusTotal", Current.UseVirusTotal }, { "VirusTotalKey", Current.VirusTotalKey } }; string preferencesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Preferences"); string preferencesFilePath = Path.Combine(preferencesPath, "com.claunia.museum.apprepodbmgr.plist"); var fs = new FileStream(preferencesFilePath, FileMode.Create); BinaryPropertyListWriter.Write(fs, root); fs.Close(); } break; case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: case PlatformID.WindowsPhone: { RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true)?. CreateSubKey("Canary Islands Computer Museum"); RegistryKey key = parentKey?.CreateSubKey("AppRepoDBMgr"); if (key != null) { key.SetValue("TemporaryFolder", Current.TemporaryFolder); key.SetValue("DatabasePath", Current.DatabasePath); key.SetValue("RepositoryPath", Current.RepositoryPath); if (Current.UnArchiverPath != null) { key.SetValue("UnArchiverPath", Current.UnArchiverPath); } key.SetValue("CompressionAlgorithm", Current.CompressionAlgorithm); key.SetValue("UseAntivirus", Current.UseAntivirus); key.SetValue("UseClamd", Current.UseClamd); key.SetValue("ClamdHost", Current.ClamdHost == null ? "" : Current.ClamdHost); key.SetValue("ClamdPort", Current.ClamdPort); key.SetValue("ClamdIsLocal", Current.ClamdIsLocal); key.SetValue("UseVirusTotal", Current.UseVirusTotal); key.SetValue("VirusTotalKey", Current.VirusTotalKey == null ? "" : Current.VirusTotalKey); } } break; default: { string configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config"); string settingsPath = Path.Combine(configPath, "AppRepoDBMgr.xml"); if (!Directory.Exists(configPath)) { Directory.CreateDirectory(configPath); } var fs = new FileStream(settingsPath, FileMode.Create); var xs = new XmlSerializer(Current.GetType()); xs.Serialize(fs, Current); fs.Close(); } break; } } #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body catch #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body { if (Debugger.IsAttached) { throw; } } }
private void loadConfig() { int i; rootKey = Microsoft.Win32.Registry.CurrentUser; softwareKey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix\lines"); i=0; foreach(string key in softwareKey.GetSubKeyNames()) { string name,code,rss; bool active,loop; int num, time; RegistryKey tempkey; tempkey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix\lines\"+key); num = (int)tempkey.GetValue("num",0); time = (int)tempkey.GetValue("time",0); loop = (string)tempkey.GetValue("loop","True") == "True"; name = (string)tempkey.GetValue("name",""); code = (string)tempkey.GetValue("code",""); rss = (string)tempkey.GetValue("rss",""); active = (string)tempkey.GetValue("active","True") == "True"; user_lines.Add(new userLine(name,active,code,rss,num,loop,time)); Console.WriteLine(key); i++; } if(i==0) { user_lines.Add(new userLine("Spiegel.de",false,"%c%r%8%h:%m:%s%n%g%-%R" ,"http://www.spiegel.de/index.rss",user_lines.Count+1,true,10)); user_lines.Add(new userLine("kicker.de",false,"%c%r%8%h:%m:%s%n%g%-%R" ,"http://rss.kicker.de/live/bundesliga",user_lines.Count+1,true,10)); user_lines.Add(new userLine("Uhrzeit",true,"%2%+%+%c%r%h:%m:%s" ,"",user_lines.Count+1,true,10)); user_lines.Add(new userLine("Wetter",false,"%c%r%8%h:%m:%s%n%g%-%R" ,"http://wetter.bjoern-b.de/daten.xml",user_lines.Count+1,true,10)); user_lines.Add(new userLine("Weihnachten",false,"%+%+%g%2%T%1%c%+%-%-%-%-%rFrohe%2 %g%+%+%+%T%n%r%1%c%-%-%-%-Weihnachten" ,"",user_lines.Count+1,false,10)); } user_lines.Sort(); softwareKey = rootKey.CreateSubKey (@"SOFTWARE\Mono.mLedMatrix"); led_matrix_address = (string)softwareKey.GetValue("ip_address","192.168.0.222"); led_matrix.setAddress(led_matrix_address); winamp.winamp_address = (string)softwareKey.GetValue("winamp_address","localhost"); winamp.winamp_port = (int)softwareKey.GetValue("winamp_port",4800); winamp.winamp_pass = (string)softwareKey.GetValue("winamp_pass","pass"); entry_winamp_address.Text = winamp.winamp_address; entry_winamp_port.Text = winamp.winamp_port.ToString(); entry_winamp_pass.Text = winamp.winamp_pass; entry_address.Text = led_matrix_address; led_matrix.scroll_speed = (int)softwareKey.GetValue("scroll_speed",10); hscale_shift_speed.Value = led_matrix.scroll_speed; //entry_static_text.Text = (string)softwareKey.GetValue("static_text") }
public static void SaveSettings() { try { PlatformID ptId = DetectOS.GetRealPlatformID(); switch (ptId) { // In case of macOS or iOS settings will be saved in ~/Library/Preferences/com.claunia.discimagechef.plist case PlatformID.MacOSX: case PlatformID.iOS: { NSDictionary root = new NSDictionary { { "SaveReportsGlobally", Current.SaveReportsGlobally }, { "ShareReports", Current.ShareReports }, { "GdprCompliance", Current.GdprCompliance } }; if (Current.Stats != null) { NSDictionary stats = new NSDictionary { { "ShareStats", Current.Stats.ShareStats }, { "BenchmarkStats", Current.Stats.BenchmarkStats }, { "CommandStats", Current.Stats.CommandStats }, { "DeviceStats", Current.Stats.DeviceStats }, { "FilesystemStats", Current.Stats.FilesystemStats }, { "FilterStats", Current.Stats.FilterStats }, { "MediaImageStats", Current.Stats.MediaImageStats }, { "MediaScanStats", Current.Stats.MediaScanStats }, { "PartitionStats", Current.Stats.PartitionStats }, { "MediaStats", Current.Stats.MediaStats }, { "VerifyStats", Current.Stats.VerifyStats } }; root.Add("Stats", stats); } string preferencesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Preferences"); string preferencesFilePath = Path.Combine(preferencesPath, "com.claunia.discimagechef.plist"); FileStream fs = new FileStream(preferencesFilePath, FileMode.Create); BinaryPropertyListWriter.Write(fs, root); fs.Close(); } break; #if !NETSTANDARD2_0 // In case of Windows settings will be saved in the registry: HKLM/SOFTWARE/Claunia.com/DiscImageChef case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: case PlatformID.WindowsPhone: { RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true)?.CreateSubKey("Claunia.com"); RegistryKey key = parentKey?.CreateSubKey("DiscImageChef"); if (key != null) { key.SetValue("SaveReportsGlobally", Current.SaveReportsGlobally); key.SetValue("ShareReports", Current.ShareReports); key.SetValue("GdprCompliance", Current.GdprCompliance); if (Current.Stats != null) { key.SetValue("Statistics", true); key.SetValue("ShareStats", Current.Stats.ShareStats); key.SetValue("BenchmarkStats", Current.Stats.BenchmarkStats); key.SetValue("CommandStats", Current.Stats.CommandStats); key.SetValue("DeviceStats", Current.Stats.DeviceStats); key.SetValue("FilesystemStats", Current.Stats.FilesystemStats); key.SetValue("FilterStats", Current.Stats.FilterStats); key.SetValue("MediaImageStats", Current.Stats.MediaImageStats); key.SetValue("MediaScanStats", Current.Stats.MediaScanStats); key.SetValue("PartitionStats", Current.Stats.PartitionStats); key.SetValue("MediaStats", Current.Stats.MediaStats); key.SetValue("VerifyStats", Current.Stats.VerifyStats); } else { key.SetValue("Statistics", true); key.DeleteValue("ShareStats", false); key.DeleteValue("BenchmarkStats", false); key.DeleteValue("CommandStats", false); key.DeleteValue("DeviceStats", false); key.DeleteValue("FilesystemStats", false); key.DeleteValue("MediaImageStats", false); key.DeleteValue("MediaScanStats", false); key.DeleteValue("PartitionStats", false); key.DeleteValue("MediaStats", false); key.DeleteValue("VerifyStats", false); } } } break; #endif // Otherwise, settings will be saved in ~/.config/DiscImageChef.xml default: { string homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string xdgConfigPath = Path.Combine(homePath, Environment.GetEnvironmentVariable(XDG_CONFIG_HOME) ?? XDG_CONFIG_HOME_RESOLVED); string settingsPath = Path.Combine(xdgConfigPath, "DiscImageChef.xml"); if (!Directory.Exists(xdgConfigPath)) { Directory.CreateDirectory(xdgConfigPath); } FileStream fs = new FileStream(settingsPath, FileMode.Create); XmlSerializer xs = new XmlSerializer(Current.GetType()); xs.Serialize(fs, Current); fs.Close(); } break; } } #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body catch { // ignored } #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body }