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

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

559 Examples 7

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

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

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

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

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

19 View Source File : ShellHost.cs
License : GNU General Public License v3.0
Project Creator : belowaverage-org

private void MsMiOptionsSubItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            mi.Checked = !mi.Checked;
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced", true);
            string tag = (string)mi.Tag;
            string name = tag.Substring(1);
            int set = 0;
            if (tag[0] == '0' && mi.Checked) set = 1;
            if (tag[0] == '1' && !mi.Checked) set = 1;
            key.SetValue(name, set);
            key.Close();
            MessageBox.Show("In order for these changes to take effect, right click anywhere in the file explorer window and select \"Refresh\".", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

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

protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            if (_currentUri != null)
                try
                {
                    using (RegistryKey rk = Config.OpenUserInstanceKey("Dialogs"))
                    {
                        rk.SetValue("Last Repository", _currentUri.ToString());
                    }
                }
                catch
                { }
        }

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

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

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

19 View Source File : Config.cs
License : GNU General Public License v3.0
Project Creator : arunsatyarth

public void SetLaunchOnStartup(bool set)
        {
            try
            {
                string regKeystr = "OneMiner";
                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if(set)
                {
                    if (rkApp.GetValue(regKeystr) == null)
                    {
                        rkApp.SetValue(regKeystr, Application.ExecutablePath);
                    }
                    else
                    {
                        Logger.Instance.LogInfo("Item is alredy there in startup");
                    }
                }
                else
                {
                    if (rkApp.GetValue(regKeystr) == null)
                    {
                        Logger.Instance.LogInfo("Item is not there in  startup anyway");
                    }
                    else
                    {
                        rkApp.DeleteValue(regKeystr, false);
                    }
                }
         
            }
            catch (Exception e)
            {
            }
     
        }

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

public void Add(string item)
        {
            if (item == null)
                throw new ArgumentNullException("item");
            else if (!_allowWhiteSpace && string.IsNullOrEmpty(item))
                return; // Don't add whitepace

            using (RegistryKey key = OpenFifoKey(false))
            {
                int nSize;
                int nPos;
                if (!RegistryUtils.TryGetIntValue(key, "_size", out nSize) || nSize < 1)
                {
                    nSize = _defaultSize;
                    key.SetValue("_size", _defaultSize);
                }

                // This gives a very tiny race condition if used at the same time in 
                // two VS instances.
                // We ignore this as it is just UI helper code and a user can't edit
                //  two windows at the same time
                if (!RegistryUtils.TryGetIntValue(key, "_pos", out nPos) || (nPos < 0) || (nPos >= nSize))
                {
                    nPos = 0;
                }

                if (nPos < 0 || nPos >= nSize)
                {
                    List<string> names = new List<string>(key.GetValueNames());

                    int nX = nSize;
                    for (int i = nSize - 1; i >= 0; i--)
                    {
                        if (names.Contains("#" + i.ToString(CultureInfo.InvariantCulture)))
                            break;

                        nX = i;
                    }

                    if (nX < nSize)
                        nPos = nX;
                    else
                        nPos = 0;
                }


                nPos++;

                if (nPos > nSize)
                    nPos = 0;

                key.SetValue("_pos", nPos);
                key.SetValue("#" + nPos.ToString(CultureInfo.InvariantCulture), item);
            }
        }

19 View Source File : AyFuncRegisterTable.cs
License : MIT License
Project Creator : ay2015

public void Write(string name, object tovalue)
        {
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey software = hklm.OpenSubKey("SOFTWARE", true);
            RegistryKey aimdir = software.CreateSubKey(AyFuncConfig.TableSoftwareName);
            aimdir.SetValue(name, tovalue);
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private static void MigrateProfiles(string DeviceType)
        {
            const string IP_ADDRESS_NOT_PRESENT = "IP Address NOT present";
            try
            {
                TL.LogMessage("MigrateProfiles", string.Format("Migrating device type {0}", DeviceType));

                for (int i = 1; i <= 2; i++)
                {
                    string webProgIdKeyName = string.Format(@"SOFTWARE\ASCOM\{0} Drivers\ASCOM.Web{1}.{0}", DeviceType, i);
                    TL.LogMessage("MigrateProfiles", string.Format("Processing registry value: {0}", webProgIdKeyName));

                    RegistryKey webProgIdKey = Registry.LocalMachine.OpenSubKey(webProgIdKeyName, true); // Open the key for writing
                    if (!(webProgIdKey == null)) // ProgID exists
                    {
                        string ipAddress = (string)webProgIdKey.GetValue("IP Address", IP_ADDRESS_NOT_PRESENT);
                        TL.LogMessage("MigrateProfiles", string.Format("Found IP Address: {0}", ipAddress));

                        if (!(ipAddress == IP_ADDRESS_NOT_PRESENT))// IP Address value exists so we need to try and rename this profile
                        {
                            // Does a current ASCOM>remoteX profile exist, if so then we can't migrate so leave as is
                            string remoteProgIdkeyName = string.Format(@"SOFTWARE\ASCOM\{0} Drivers\ASCOM.Remote{1}.{0}", DeviceType, i);
                            TL.LogMessage("MigrateProfiles", string.Format("Checking whether registry key {0} exists", remoteProgIdkeyName));

                            RegistryKey remoteProgIdKey = Registry.LocalMachine.OpenSubKey(remoteProgIdkeyName, true); // Open the key for writing
                            if (remoteProgIdKey == null) // The "Remote" Profile does not exist so we can just rename the "Web" profile
                            {
                                TL.LogMessage("MigrateProfiles", string.Format("The registry key {0} does not exist - creating it", remoteProgIdkeyName));
                                Registry.LocalMachine.CreateSubKey(remoteProgIdkeyName, true);
                                remoteProgIdKey = Registry.LocalMachine.OpenSubKey(remoteProgIdkeyName, true); // Open the key for writing
                                TL.LogMessage("MigrateProfiles", string.Format("Registry key {0} created OK", remoteProgIdkeyName));
                                string[] valueNames = webProgIdKey.GetValueNames();
                                foreach (string valueName in valueNames)
                                {
                                    string value;

                                    if (valueName == "") // Special handling for the default value - need to change chooser description to ASCOM Remote Client X
                                    {
                                        value = string.Format("ASCOM Remote Client {0}", i);
                                        TL.LogMessage("MigrateProfiles", string.Format("Changing Chooser description to {0} ", value));
                                    }
                                    else
                                    {
                                        value = (string)webProgIdKey.GetValue(valueName);
                                        TL.LogMessage("MigrateProfiles", string.Format("Found Web registry value name {0} = {1}", valueName, value));
                                    }
                                    TL.LogMessage("MigrateProfiles", string.Format("Setting Remote registry value {0} to {1}", valueName, value));
                                    remoteProgIdKey.SetValue(valueName, value);
                                }
                                TL.LogMessage("MigrateProfiles", string.Format("Driver successfully migrated - deleting Profile {0}", webProgIdKeyName));
                                Registry.LocalMachine.DeleteSubKey(webProgIdKeyName);
                                TL.LogMessage("MigrateProfiles", string.Format("Successfully deleted Profile {0}", webProgIdKeyName));
                            }
                            else // The "Remote" profile already exists so we can't migrate the old "Web" profile
                            {
                                TL.LogMessage("MigrateProfiles", string.Format("The {0} key already exists so we cannot migrate the {1} profile - no action taken", remoteProgIdkeyName, webProgIdKeyName));
                            }
                        }
                        else // No IP address value means that this profile is unconfigured so just delete it.
                        {
                            TL.LogMessage("MigrateProfiles", string.Format("Driver not configured - deleting Profile {0}", webProgIdKeyName));
                            Registry.LocalMachine.DeleteSubKey(webProgIdKeyName);
                            TL.LogMessage("MigrateProfiles", string.Format("Successfully deleted Profile {0}", webProgIdKeyName));
                        }
                    }
                    else // ProgID doesn't exist
                    {
                        TL.LogMessage("MigrateProfiles", string.Format("ProgId {0} does not exist - no action taken", webProgIdKeyName));
                    }
                }
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("MigrateProfiles", ex.ToString());
            }
        }

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

public void SetValue<T>(string KeyName, string SubKey, T Value)
        {
            if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "SetValue", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString()));

            if (SubKey == "") baseRegistryKey.SetValue(KeyName, Value.ToString());
            else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, Value.ToString());
        }

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

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

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

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

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

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

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

19 View Source File : ShellExtLib.cs
License : MIT License
Project Creator : Autodesk-Forge

public static void RegisterShellExtContextMenuHandler(Guid clsid,
        string fileType, string friendlyName)
    {
      if (clsid == Guid.Empty)
      {
        throw new ArgumentException("clsid must not be empty");
      }
      if (string.IsNullOrEmpty(fileType))
      {
        throw new ArgumentException("fileType must not be null or empty");
      }

      // If fileType starts with '.', try to read the default value of the 
      // HKCR\<File Type> key which contains the ProgID to which the file type 
      // is linked.
      if (fileType.StartsWith("."))
      {
        using (RegistryKey key = Registry.ClreplacedesRoot.OpenSubKey(fileType))
        {
          if (key != null)
          {
            // If the key exists and its default value is not empty, use 
            // the ProgID as the file type.
            string defaultVal = key.GetValue(null) as string;
            if (!string.IsNullOrEmpty(defaultVal))
            {
              fileType = defaultVal;
            }
          }
        }
      }

      // Create the key HKCR\<File Type>\shellex\ContextMenuHandlers\{<CLSID>}.
      string keyName = string.Format(@"{0}\shellex\ContextMenuHandlers\{1}",
          fileType, clsid.ToString("B"));
      using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(keyName))
      {
        // Set the default value of the key.
        if (key != null && !string.IsNullOrEmpty(friendlyName))
        {
          key.SetValue(null, friendlyName);
        }
      }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                Application.EnableVisualStyles();

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

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

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

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

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

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

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

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

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

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

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

                    ShowGettingStarted();

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

                testActionWindow = new TestActionWindow();

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

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

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

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

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

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

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

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

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

                Application.Run();
            }

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

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

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

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

19 View Source File : AutoStart.cs
License : MIT License
Project Creator : awaescher

public static void SetStartup(string appName, bool startup)
		{
			var key = Registry.CurrentUser.OpenSubKey(REG_KEY, true);

			if (startup)
				key.SetValue(appName, GetAppPath());
			else
				key.DeleteValue(appName, false);
		}

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

public void SetInt(string strName, int iValue)
        {
            m_Key.SetValue(strName, iValue);
        }

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

private void SetStartup()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            rk.SetValue("RoundedScreen", Process.GetCurrentProcess().MainModule.FileName);
            Debug.WriteLine(Process.GetCurrentProcess().MainModule.FileName);
        }

19 View Source File : RegistryHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void SetStringValue(RegistryKey key, string name, string val)
        {
            key.SetValue(name, val);
            key.Flush();
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

19 View Source File : Functions.cs
License : MIT License
Project Creator : arsium

internal static void SetWallPaper(byte[] file, string ext) 
		{
			byte[] decompressed = Shared.Compressor.QuickLZ.Decompress(file);
			string path1 = Path.Combine(Path.GetTempFileName() + ext);
			string path2 = Path.Combine(Path.GetTempFileName() + ext);
			File.WriteAllBytes(path1, decompressed);

			using (Bitmap bmp = new Bitmap(path1))
			using (Graphics graphics = Graphics.FromImage(bmp))
			{
				bmp.Save(path2, ImageFormat.Bmp);
			}
			using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true))
			{
				key.SetValue("WallpaperStyle", 2.ToString());
				key.SetValue("TileWallpaper", 0.ToString());
			}
			NativeAPI.Miscellaneous.SystemParametersInfo(NativeAPI.Miscellaneous.SPI_SETDESKWALLPAPER, 0, path2, NativeAPI.Miscellaneous.SPIF_UPDATEINIFILE | NativeAPI.Miscellaneous.SPIF_SENDWININICHANGE);
		}

19 View Source File : RegistryHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static bool GetBoolValue(RegistryKey key, string name, bool def)
        {
            var re = key.GetValue(name);
            if (re == null)
            {
                key.SetValue(name, def);
                key.Flush();
                return def;
            }
            return Convert.ToBoolean(re);
        }

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

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

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

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

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

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

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

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

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

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

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

19 View Source File : StartupManager.cs
License : MIT License
Project Creator : AlexGyver

private void CreateRegistryRun() {
      RegistryKey key = Registry.CurrentUser.CreateSubKey(REGISTRY_RUN);     
      key.SetValue("OpenHardwareMonitor", Application.ExecutablePath);
    }

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

public void SetValue<T>(string KeyName, string SubKey, T Value)
        {
            if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "SetValue", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString()));

            if (SubKey == "") baseRegistryKey.SetValue(KeyName, Value.ToString());
            else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, Value.ToString());
        }

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

public void SetValueInvariant<T>(string KeyName, string SubKey, T Value)
        {
            if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "SetValue DateTime", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString()));

            if ((typeof(T) == typeof(Int32)) | (typeof(T) == typeof(int)))
            {
                int intValue = Convert.ToInt32(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, intValue.ToString(CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, intValue.ToString(CultureInfo.InvariantCulture));
                return;
            }

            if (typeof(T) == typeof(bool))
            {
                bool boolValue = Convert.ToBoolean(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, boolValue.ToString(CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, boolValue.ToString(CultureInfo.InvariantCulture));
                return;
            }

            if (typeof(T) == typeof(decimal))
            {
                decimal decimalValue = Convert.ToDecimal(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, decimalValue.ToString(CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, decimalValue.ToString(CultureInfo.InvariantCulture));
                return;
            }

            if (typeof(T) == typeof(DateTime))
            {
                DateTime dateTimeValue = Convert.ToDateTime(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, dateTimeValue.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, dateTimeValue.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
                return;
            }

            throw new DriverException("SetValueInvariant: Unknown type: " + typeof(T).Name);
        }

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

private void OnResponse(IAsyncResult ar)
        {
            IAnkhConfigurationService config = Context.GetService<IAnkhConfigurationService>();
            bool failed = true;
            string tag = null;
            try
            {
                WebRequest rq = ((WebRequest)ar.AsyncState);
                WebResponse wr;
                try
                {
                    wr = rq.EndGetResponse(ar);
                }
                catch (WebException e)
                {
                    HttpWebResponse hwr = e.Response as HttpWebResponse;

                    if (hwr != null)
                    {
                        if (hwr.StatusCode == HttpStatusCode.NotFound)
                        {
                            failed = false;
                            return; // File not found.. Update info not yet or no longer available
                        }
                    }

                    return;
                }
                catch
                {
                    return;
                }

                if (wr.ContentLength > 65536) // Not for us.. We expect a few hundred bytes max
                    return;

                string body;
                using (Stream s = wr.GetResponseStream())
                using (StreamReader sr = new StreamReader(s))
                {
                    body = sr.ReadToEnd().Trim();
                }

                if (string.IsNullOrEmpty(body))
                {
                    failed = false;
                    return;
                }

                if (body[0] != '<' || body[body.Length - 1] != '>')
                    return; // No valid xml or empty

                failed = false;

                XmlDoreplacedent doc = new XmlDoreplacedent();
                doc.LoadXml(body);

                string replacedle = NodeText(doc, "/u/i/t");
                string header = NodeText(doc, "/u/i/h") ?? replacedle;
                string description = NodeText(doc, "/u/i/d");
                string url = NodeText(doc, "/u/i/u");
                string urltext = NodeText(doc, "/u/i/l");

                string version = NodeText(doc, "/u/i/v");
                string newVersion = NodeText(doc, "/u/i/n") ?? version;

                tag = NodeText(doc, "/u/g");

                if (!string.IsNullOrEmpty(replacedle) && !string.IsNullOrEmpty(description))
                {
                    if (!string.IsNullOrEmpty(version))
                    {
                        Version v = new Version(version);

                        if (v <= GetCurrentVersion(Context))
                            return;
                    }

                    if (!string.IsNullOrEmpty(tag))
                    {
                        using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
                        {
                            string pTag = rk.GetValue("SkipTag") as string;

                            if (pTag == tag)
                                return;
                        }
                    }

                    IAnkhCommandService cs = Context.GetService<IAnkhCommandService>();

                    cs.PostExecCommand(AnkhCommand.CheckForUpdates,
                        new string[] { replacedle, header, description, url, urltext, version, newVersion, tag });
                }
            }
            finally
            {
                using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
                {
                    object fails = rk.GetValue("Fails", 0);
                    rk.DeleteValue("LastCheck", false);
                    rk.DeleteValue("LastVersion", false);
                    rk.DeleteValue("FailedChecks", false);
                    rk.SetValue("LastCheck", DateTime.UtcNow.Ticks);
                    rk.SetValue("LastVersion", GetCurrentVersion(Context).ToString());
                    if (tag != null)
                        rk.SetValue("LastTag", tag);
                    else
                        rk.DeleteValue("LastTag", false);

                    if (failed)
                    {
                        int f = 0;
                        if (fails is int)
                            f = (int)fails + 1;

                        rk.SetValue("FailedChecks", f);
                    }
                }
            }
        }

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

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

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

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

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

19 View Source File : UpdateManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public void WritebackUpdate()
        {
            using (RegistryKey softwareKey = Registry.CurrentUser.CreateSubKey("Software"),
                   sdKey = softwareKey.CreateSubKey("StarDisplay"))
            {
                sdKey.SetValue("updatecfg", UpdateVersion());
            }
        }

19 View Source File : FileAssociation.cs
License : GNU General Public License v3.0
Project Creator : audiamus

private static bool setKeyValue (string keyPath, string value, string name = null) {
      bool dirty = false;
      // does key exist?
      using (var key = Registry.CurrentUser.OpenSubKey (keyPath)) {
        dirty = key is null;
      }

      using (var key = Registry.CurrentUser.CreateSubKey (keyPath)) {
        if (name is null) {
          if (key.GetValue (name) as string != value) {
            key.SetValue (name, value);
            dirty = true;
          }
        } else {
          var names = key.GetValueNames ();
          if (names.Contains (name)) {
            if (key.GetValue (name) as string != value) {
              key.SetValue (name, value);
              dirty = true;
            } 
          } else { 
            key.SetValue (name, value);
            dirty = true;
          }
        }
      }

      return dirty;
    }

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

public void SetDouble(string strName, double dValue)
        {
            byte[] arBytes = BitConverter.GetBytes(dValue);
            m_Key.SetValue(strName, arBytes);
        }

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

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

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

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

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

19 View Source File : RegistryHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string GetStringValue(RegistryKey key, string name, string def)
        {
            var re = key.GetValue(name);
            if (re == null)
            {
                key.SetValue(name, def);
                key.Flush();
                return def;
            }
            return re.ToString();
        }

19 View Source File : RegistryFusionService.cs
License : MIT License
Project Creator : awaescher

private void WriteFusionSetting<T>(string settingName, T value)
		{
			using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
			{
				using (var key = hklm.OpenSubKey(FUSION_REGISTRY_PATH, writable: true))
				{
					key.SetValue(settingName, value);
				}
			}
		}

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

public void SetString(string strName, string strValue)
        {
            m_Key.SetValue(strName, strValue);
        }

19 View Source File : AyFuncFileExtRegister.cs
License : MIT License
Project Creator : ay2015

private void SetValue(RegistryKey root, string subKey, object keyValue, string valueName)
        {
            bool hreplacedubKey = ((subKey != null) && (subKey.Length > 0));
            RegistryKey key = root;

            try
            {
                if (hreplacedubKey) key = root.CreateSubKey(subKey);
                key.SetValue(valueName, keyValue);
            }
            finally
            {
                if (hreplacedubKey && (key != null)) key.Close();
            }
        }

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

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

19 View Source File : AyFuncRegisterTable.cs
License : MIT License
Project Creator : ay2015

public void Write(RegistryKey root, string subkey, string name, string value)
        {
            RegistryKey aimdir = root.CreateSubKey(subkey);
            aimdir.SetValue(name, value);
        }

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

public void Clear()
        {
            using (RegistryKey key = OpenFifoKey(false))
            {
                key.SetValue("_pos", 0);

                string[] names = key.GetValueNames();
                Array.Sort<string>(names);

                foreach (string name in names)
                {
                    if (name.StartsWith("#"))
                        key.DeleteValue(name);
                }
            }
        }

19 View Source File : Run.cs
License : GNU General Public License v3.0
Project Creator : belowaverage-org

public void SaveMRU()
        {
            RegistryKey reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU", true);
            string sMruList = "";
            foreach (char letter in MRUList)
            {
                if (letter == '\0') continue;
                sMruList += letter;
            }
            reg.SetValue("MRUList", sMruList);
            foreach (char item in sMruList)
            {
                int mruKeyIndex = Array.IndexOf(MRUKeys, item);
                if (mruKeyIndex == -1) continue;
                reg.SetValue(item.ToString(), MRUVals[mruKeyIndex]);
            }
            reg.Close();
        }

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

public static void RegWriteValue(string path, string name, object value)
        {
            RegistryKey regKey = null;
            try
            {
                regKey = Registry.CurrentUser.CreateSubKey(path);
                if (IsNullOrEmpty(value.ToString()))
                {
                    regKey?.DeleteValue(name, false);
                }
                else
                {
                    regKey?.SetValue(name, value);
                }
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
            }
            finally
            {
                regKey?.Close();
            }
        }

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

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

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

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

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

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

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

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

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

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

            key.Close();
        }

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

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

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

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

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

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

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

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

19 View Source File : RegistryHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void SetBoolValue(RegistryKey key, string name, bool val)
        {
            key.SetValue(name, val);
            key.Flush();
        }

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

private static void ShowUpdate(CommandEventArgs e)
        {
            string[] args;

            try
            {
                args = (string[])e.Argument;
            }
            catch { return; }

            if (args == null || args.Length < 8)
                return;

            string replacedle = args[0], header = args[1], description = args[2], url = args[3],
                urltext = args[4], version = args[5], newVersion = args[6], tag = args[7];

            using (UpdateAvailableDialog uad = new UpdateAvailableDialog())
            {
                try
                {
                    uad.Text = string.Format(uad.Text, replacedle);
                    uad.headLabel.Text = header;
                    uad.bodyLabel.Text = description;
                    uad.linkLabel.Text = urltext;
                    uad.linkLabel.Links.Add(0, urltext.Length).LinkData = url;

                    if (!string.IsNullOrEmpty(version))
                    {
                        uad.newVerLabel.Text = newVersion;
                        uad.curVerLabel.Text = GetPackageVersion(e.Context).ToString(3);
                        uad.versionPanel.Enabled = uad.versionPanel.Visible = true;
                    }

                    if (string.IsNullOrEmpty(tag))
                        uad.sameCheck.Enabled = uad.sameCheck.Visible = false;
                }
                catch
                {
                    return; // Don't throw a visible exception from a background check!
                }

                uad.ShowDialog(e.Context);

                if (uad.sameCheck.Checked)
                {
                    IAnkhConfigurationService config = e.GetService<IAnkhConfigurationService>();
                    using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
                    {
                        rk.SetValue("SkipTag", tag);
                    }
                }
            }
        }

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

[STAThread]
        static void Main(string[] args)
        {

            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

            // Set the unhandled exception mode to force all exceptions to go through our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // Add the event handler for handling non-UI thread exceptions to the event. 
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            TL = new TraceLogger("", "DynamicClients");
            TL.Enabled = true;

            try
            {
                string parameter = ""; // Initialise the supplied parameter to empty string
                if (args.Length > 0) parameter = args[0]; // Copy any supplied parameter to the parameter variable

                TL.LogMessage("Main", string.Format(@"Supplied parameter: ""{0}""", parameter));
                parameter = parameter.TrimStart(' ', '-', '/', '\\'); // Remove any parameter prefixes and leading spaces
                parameter = parameter.TrimEnd(' '); // Remove any trailing spaces

                TL.LogMessage("Main", string.Format(@"Trimmed parameter: ""{0}""", parameter));

                switch (parameter.ToUpperInvariant()) // Act on the supplied parameter, if any
                {
                    case "": // Run the application in user interactive mode
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        TL.LogMessage("Main", "Starting application form");
                        Application.Run(new Form1(TL));
                        break;

                    case "INSTALLERSETUP": // Called by the installer to create drivers on first time use
                        TL.LogMessage("Main", "Running installer setup");

                        // Find if there are any driver files already installed, indicating that this is not a first time install
                        string localServerPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86) + Form1.REMOTE_SERVER_PATH;
                        string deviceType = "*";
                        string searchPattern = string.Format(Form1.REMOTE_CLIENT_DRIVER_NAME_TEMPLATE, deviceType);

                        TL.LogMessage("Main", "About to create base key");
                        RegistryKey remoteRegistryKey = RegistryKey.OpenBaseKey(SharedConstants.ASCOM_REMOTE_CONFIGURATION_HIVE, RegistryView.Default).CreateSubKey(SharedConstants.ASCOM_REMOTE_CONFIGURATION_KEY, true);
                        bool alreadyRun = bool.Parse((string)remoteRegistryKey.GetValue(ALREADY_RUN, "false"));
                        TL.LogMessage("Main", string.Format("Already run: {0}", alreadyRun));

                        if (!alreadyRun) // We have not run yet 
                        {
                            TL.LogMessage("Main", string.Format("First time setup - migrating profiles and creating dynamic drivers"));

                            // Only attempt first time setup if the local server executable is present
                            string localServerExe = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86) + Form1.REMOTE_SERVER_PATH + Form1.REMOTE_SERVER; // Get the local server path
                            if (File.Exists(localServerExe)) // Local server does exist
                            {
                                // Migrate any ASCOM.WebX.DEVICE profile entries to ASCOM.RemoteX.DEVICE profile entries
                                TL.LogMessage("Main", string.Format("Migrating any ASCOM.WebX.DEVICETYPE profiles to ASCOM.RemoteX.DEVICETYPE"));
                                MigrateProfiles("Camera");
                                MigrateProfiles("Dome");
                                MigrateProfiles("FilterWheel");
                                MigrateProfiles("Focuser");
                                MigrateProfiles("ObservingConditions");
                                MigrateProfiles("Rotator");
                                MigrateProfiles("SafetyMonitor");
                                MigrateProfiles("Switch");
                                MigrateProfiles("Telescope");

                                // Remove any driver or pdb driver files left in the , local server directory
                                DeleteFiles(localServerPath, @"ascom\.remote\d\.\w+\.dll", "ASCOM.RemoteX.DLL");
                                DeleteFiles(localServerPath, @"ascom\.remote\d\.\w+\.pdb", "ASCOM.RemoteX.PDB");
                                DeleteFiles(localServerPath, @"ascom\.web\d\.\w+\.dll", "ASCOM.WebX.DLL");
                                DeleteFiles(localServerPath, @"ascom\.web\d\.\w+\.pdb", "ASCOM.WebX.PDB");

                                // Create the required drivers
                                TL.LogMessage("Main", string.Format("Creating one remote client driver of each device type"));
                                Form1.CreateDriver("Camera", 1, localServerPath, TL);
                                Form1.CreateDriver("Dome", 1, localServerPath, TL);
                                Form1.CreateDriver("FilterWheel", 1, localServerPath, TL);
                                Form1.CreateDriver("Focuser", 1, localServerPath, TL);
                                Form1.CreateDriver("ObservingConditions", 1, localServerPath, TL);
                                Form1.CreateDriver("Rotator", 1, localServerPath, TL);
                                Form1.CreateDriver("SafetyMonitor", 1, localServerPath, TL);
                                Form1.CreateDriver("Switch", 1, localServerPath, TL);
                                Form1.CreateDriver("Telescope", 1, localServerPath, TL);

                                // Register the drivers
                                TL.LogMessage("Main", "Registering drivers");
                                Form1.RunLocalServer(localServerExe, "-regserver", TL);

                                // Record that we have run once on this PC
                                TL.LogMessage("Main", string.Format("Setting already run to true"));
                                remoteRegistryKey.SetValue(ALREADY_RUN, "true");
                                TL.LogMessage("Main", string.Format("Set already run to true"));
                            }
                            else // Local server can not be found so report the issue
                            {
                                string errorMessage = string.Format("Could not find local server {0}, unable to register drivers", localServerExe);
                                TL.LogMessage("Main", errorMessage);
                                MessageBox.Show(errorMessage);
                            }
                        }
                        else // Drivers are already installed so no action required
                        {
                            TL.LogMessage("Main", string.Format("This application has already run successful so this is not a first time installation - no action taken"));
                        }
                        break;

                    default: // Unrecognised parameter so flag this to the user
                        string errMsg = string.Format("Unrecognised parameter: {0}, the only valid value is /InstallerSetup", parameter);

                        MessageBox.Show(errMsg);
                        break;
                }
            }
            catch (Exception ex)
            {
                string errMsg = ("DynamicRemoteClients exception: " + ex.ToString());
                TL.LogMessageCrLf("Main", errMsg);
                MessageBox.Show(errMsg);
            }

            TL.Enabled = false;
            TL.Dispose();
            TL = null;
        }

See More Examples