/// <summary> /// 지정된 서브키를 지정된 접근 모드 (읽기, 읽기/쓰기) 로 연다. /// </summary> /// <param name="subKeyName">서브 키 이름</param> /// <param name="writable">true이면 읽기/쓰기여부, false이면 읽기 가능한지 여부</param> /// <returns>레지스트리 키 객체</returns> public RegistryKey OpenSubKey(string subKeyName, bool writable) { if (IsDebugEnabled) { log.Debug("지정된 서브키를 지정된 접근 모드로 연다... subKeyName=[{0}], writable=[{1}]", subKeyName, writable); } if (subKeyName.IsNotEmpty()) { return(RootKey.OpenSubKey(subKeyName, writable)); } return(null); }
/// <summary> /// 지정된 키의 하위에 있는 모든 Sub Key의 이름을 반환한다. /// </summary> /// <param name="keyName">키 이름</param> /// <returns>성공시 문자열 1차원 배열, 실패시 길이가 0인 문자열 배열을 반환한다.</returns> public string[] GetSubKeyNames(string keyName) { if (IsDebugEnabled) { log.Debug("지정된 키의 하위에 있는 모든 Sub Key의 이름을 반환한다... keyName=[{0}]", keyName); } if (keyName.IsNotEmpty()) { using (RegistryKey key = RootKey.OpenSubKey(keyName)) if (key != null) { return(key.GetSubKeyNames()); } } return(new string[0]); }
/// <summary> /// 修改注册表 /// </summary> /// <param name="key">注册表键</param> /// <param name="name">项</param> /// <param name="value">值</param> private void UpdatePortInRegedit(string key, string name, string value) { RegistryKey RootKey; RegistryKey SubKey; RootKey = Registry.LocalMachine; try { SubKey = RootKey.OpenSubKey(key, true); if (SubKey != null) { SubKey.SetValue(name, value); } SubKey.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\r" + ex.StackTrace); } }
internal override void RegisterBrowser() { //Unregister AppId. UnregisterBrowser(); RegistryKey appReg = Registry.CurrentUser.OpenSubKey("SOFTWARE", true); appReg = appReg.CreateSubKey("AdroitTechnologies", RegistryKeyPermissionCheck.ReadWriteSubTree); appReg = appReg.CreateSubKey("BrowserSelector", RegistryKeyPermissionCheck.ReadWriteSubTree); // Register capabilities. var capabilityReg = appReg.CreateSubKey("Capabilities"); capabilityReg.SetValue("ApplicationName", AppName); capabilityReg.SetValue("ApplicationIcon", AppIcon); capabilityReg.SetValue("ApplicationDescription", AppDescription); // Set up protocols we want to handle. var urlAssoc = capabilityReg.CreateSubKey("URLAssociations"); urlAssoc.SetValue("http", AppId); urlAssoc.SetValue("https", AppId); var regApps = RootKey.OpenSubKey(@"SOFTWARE\RegisteredApplications", true); regApps.SetValue(AppId, @"SOFTWARE\AdroitTechnologies\BrowserSelector\Capabilities"); string keyName = @"SOFTWARE\Classes\" + AppId; var classesReg = Registry.CurrentUser.CreateSubKey(keyName); classesReg.SetValue("", AppName); classesReg.CreateSubKey("DefaultIcon").SetValue("", AppIcon); classesReg.CreateSubKey("shell\\open\\command").SetValue("", AppOpenUrlCommand); classesReg = RootKey.CreateSubKey(keyName); classesReg.SetValue("", AppName); classesReg.CreateSubKey("DefaultIcon").SetValue("", AppIcon); classesReg.CreateSubKey("shell\\open\\command").SetValue("", AppOpenUrlCommand); }
public static void Register(Type type) { string ProgID = type.FullName; string Version = type.Assembly.GetName().Version.ToString(); string GUIDstr = "{" + type.GUID.ToString() + "}"; string keyPath = @"Software\Classes\"; RegistryKey regularx86View = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32); RegistryKey regularx64View = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64); RegistryKey[] keys = { regularx86View.OpenSubKey(keyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl), regularx64View.OpenSubKey(keyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl) }; ProgIdAttribute[] attributes = (ProgIdAttribute[])type.GetCustomAttributes(typeof(ProgIdAttribute), false); if (attributes.Length > 0) { ProgID = attributes[0].Value; } foreach (RegistryKey RootKey in keys) { //[HKEY_CURRENT_USER\Software\Classes\Prog.ID] //@="Namespace.Class" RegistryKey keyProgID = RootKey.CreateSubKey(ProgID); keyProgID.SetValue(null, type.FullName); //[HKEY_CURRENT_USER\Software\Classes\Prog.ID\CLSID] //@="{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" keyProgID.CreateSubKey(@"CLSID").SetValue(null, GUIDstr); //[HKEY_CURRENT_USER\Software\Classes\CLSID\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}] //@="Namespace.Class // //sRegistryKey keyCLSID = RootKey.OpenSubKey(@"CLSID", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl).CreateSubKey(GUIDstr); RegistryKey keyCLSID = RootKey.OpenSubKey(@"CLSID", true); if (keyCLSID == null) { keyCLSID = RootKey.CreateSubKey("CLSID", RegistryKeyPermissionCheck.ReadWriteSubTree); } keyCLSID = keyCLSID.CreateSubKey(GUIDstr); keyCLSID.SetValue(null, type.FullName); //[HKEY_CURRENT_USER\Software\Classes\CLSID\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\ProgId] //@="Prog.ID" keyCLSID.CreateSubKey("ProgId").SetValue(null, ProgID); //[HKEY_CURRENT_USER\Software\Classes\CLSID\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\InprocServer32] //@="mscoree.dll" //"ThreadingModel"="Both" //"Class"="Namespace.Class" //"Assembly"="AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=71c72075855a359a" //"RuntimeVersion"="v4.0.30319" //"CodeBase"="file:///Drive:/Full/Image/Path/file.dll" RegistryKey InprocServer32 = keyCLSID.CreateSubKey("InprocServer32"); SetInprocServer(InprocServer32, type, false); //[HKEY_CURRENT_USER\Software\Classes\CLSID\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\InprocServer32\1.0.0.0] //"Class"="Namespace.Class" //"Assembly"="AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=71c72075855a359a" //"RuntimeVersion"="v4.0.30319" //"CodeBase"="file:///Drive:/Full/Image/Path/file.dll" SetInprocServer(InprocServer32.CreateSubKey("Version"), type, true); //[HKEY_CURRENT_USER\Software\Classes\CLSID\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\Implemented Categories\{62C8FE65-4EBB-45E7-B440-6E39B2CDBF29}] keyCLSID.CreateSubKey(@"Implemented Categories\{62C8FE65-4EBB-45E7-B440-6E39B2CDBF29}"); keyCLSID.Close(); } }
public RegistryKey OpenReadonly(string path) { string key = SubKey + '\\' + path; return(RootKey.OpenSubKey(key)); }
static void Main(string[] args) { string RequestedDeviceStatus = "Active"; // Initialize string variable for storing audio device status of interest. Valid input = "Active" or "Enabled" string RequestedDeviceType = "Playback"; // Initialize string variable for storing audio device type of interest. Valid input = "Playback" or "Recording" if (!String.Equals(RequestedDeviceStatus, "Active", StringComparison.OrdinalIgnoreCase) && !String.Equals(RequestedDeviceStatus, "Enabled", StringComparison.OrdinalIgnoreCase)) // Check RequestedDeviceStatus to ensure valid input was provided { Console.WriteLine("Invalid AudioDeviceStatus specified. Info request canceled"); // Output info to event log Console.ReadLine(); // Wait for user input return; // Immediately stop processing the inline function } string DeviceRegistryName; // Declare string variable for storing the registry name for the device type of interest if (String.Equals(RequestedDeviceType, "Playback", StringComparison.OrdinalIgnoreCase)) // Check if info request is for playback devices { DeviceRegistryName = "Render"; // Set the DeviceRegistryName } else if (String.Equals(RequestedDeviceType, "Recording", StringComparison.OrdinalIgnoreCase)) // Check if info request is for recording devices { DeviceRegistryName = "Capture"; // Set the DeviceRegistryName } else { Console.WriteLine("Invalid AudioDeviceType specified. Info request canceled"); // Output info to event log Console.ReadLine(); // Wait for user input return; // Immediately stop processing the inline function } RegistryKey RootKey; // Initialize RegistryKey for containing the root (base) key to evaluate if (Environment.Is64BitOperatingSystem) // Check if operating system is 64-bit { RootKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); // Opens registry's LocalMachine key with a 64-bit view } else { RootKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); // Opens registry's LocalMachine key with a 32-bit view } string AudioKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio"; // Parent registry key for audio devices string DeviceName, DeviceType; // Declare string variables for storing audio device information string[] ActiveDeviceRoles = null; // Initialize string array for storing information about the active devices for each audio role using (RegistryKey ChildKey = RootKey.OpenSubKey(AudioKey)) // Open subkey of AudioKey and store in ChildKey. "using" implemented for proper disposal. { foreach (string ChildKeyName in ChildKey.GetSubKeyNames()) // Loop through each SubKeyName in ChildKey { if (ChildKeyName == DeviceRegistryName) // Check if ChildKeyName is "Render" (signifies registry folder for audio playback devices) { using (RegistryKey RenderKey = ChildKey.OpenSubKey(ChildKeyName)) // Open subkey of ChildKey and store in RenderKey. "using" implemented for proper disposal. { DateTime[] ActiveDeviceRoleTimes = null; // Initialize DateTime array for storing times when audio devices last held a particular audio role int j = 1; // Initialize integer variable for tracking audio playback device count foreach (string DeviceKeyName in RenderKey.GetSubKeyNames()) // Loop through each SubKeyName in RenderKey { using (RegistryKey DeviceKey = RenderKey.OpenSubKey(DeviceKeyName)) // Open subkey of RenderKey and store in DeviceKey. "using" implemented for proper disposal. { if (Convert.ToInt32(DeviceKey.GetValue("DeviceState")) == 1) // Check if current audio device is enabled { string CurrentDeviceInfo; // Declare string variable for storing information about the current audio device using (RegistryKey DeviceKeyProperties = DeviceKey.OpenSubKey("Properties")) // Open "Properties" subkey of DeviceKey and store in DeviceKeyProperties. "using" implemented for proper disposal. { DeviceName = DeviceKeyProperties.GetValue("{b3f8fa53-0004-438e-9003-51a46e139bfc},6").ToString(); // Retrieve the current device's name from the registry DeviceType = DeviceKeyProperties.GetValue("{a45c254e-df1c-4efd-8020-67d146a850e0},2").ToString(); // Retrieve the current device's type from the registry CurrentDeviceInfo = DeviceType + " (" + DeviceName + ")"; // Combine the DeviceName and DeviceType info similar to how VoiceAttack displays this data in the Options menu if (String.Equals(RequestedDeviceStatus, "Enabled", StringComparison.OrdinalIgnoreCase)) // Check if user wants to show which audio devices are enabled { Console.WriteLine("Audio " + RequestedDeviceType + " Device " + j++ + " = " + CurrentDeviceInfo); // Output the CurrentDeviceInfo to the event log continue; // Continue with next index in parent for loop } } string[] roles = { "Role:0", "Role:1", "Role:2" }; // Initialize string array for storing the names of the different audio roles DateTime[] CurrentDeviceRoleTimes = new DateTime[roles.Length]; // Initialize DateTime array for storing times when the current audio devices last held a particular audio role //Console.WriteLine("Audio " + RequestedDeviceType + " Device " + j++ + " = " + CurrentDeviceInfo); // Output the CurrentDeviceInfo to the event log. Useful for debuging for (int i = 0; i < roles.Length; i++) // Loop based on the size of the roles string array { byte[] RegistryData = (byte[])DeviceKey.GetValue(roles[i]); // Extract audio device role data from the registry if (RegistryData == null) // Check if the extracted data is null { continue; // Continue to next index in parent for loop } CurrentDeviceRoleTimes[i] = GetRoleDateTime(RegistryData); // Retrieve role information from registry, convert this data to a DateTime, and store it //Console.WriteLine(roles[i] + " = " + CurrentDeviceRoleTimes[i].ToString()); // Output info to event log. Useful for debuging } if (ActiveDeviceRoles == null || ActiveDeviceRoles.Length == 0) // Check if ActiveDeviceRoles is null or empty { ActiveDeviceRoles = new string[roles.Length]; // Initialize ActiveDeviceRoles string array ActiveDeviceRoleTimes = new DateTime[roles.Length]; // Initialize ActiveDeviceRoleTImes DateTime array } for (int i = 0; i < roles.Length; i++) // Loop based on the size of the roles string array { if (ActiveDeviceRoleTimes[i] < CurrentDeviceRoleTimes[i]) // Check if the ActiveDeviceRoleTime at the current index is less than the CurrentDeviceRoleTime at this index { ActiveDeviceRoles[i] = CurrentDeviceInfo; // Set ActiveDeviceRoles at current index to CurrentDeviceInfo ActiveDeviceRoleTimes[i] = CurrentDeviceRoleTimes[i]; // Set ActiveDeviceRoleTime at current index to corresponding CurrentDeviceRoleTime at this index } } } } } } } } } if (!String.Equals(RequestedDeviceStatus, "Enabled", StringComparison.OrdinalIgnoreCase)) // Check if user does NOT want to see the enabled devices { if (ActiveDeviceRoles != null) // Check if ActiveDeviceRoles is not null (i.e., enabled device data has been found and stored) { for (int i = 0; i < ActiveDeviceRoles.Length; i++) // Loop based on the size of the ActiveDeviceRoles string array { string RoleName = null; // Initialize string variable for storing role description switch (i) // Create switch statement based on integer i { case 0: // For case where i = 0 RoleName = "Default"; // Set RoleName break; // Break out of switch statement case 1: // For case where i = 1 // There is the "Multimedia" role, but I don't believe this is currently used by Windows. // The code for this role will remain for possible future use. //RoleName = "Multimedia"; // Set RoleName //break; // Break out of switch statement continue; // Immediately continue with next index in parent for loop case 2: // For case where i = 2 RoleName = "Communications"; // Set RoleName break; // Break out of switch statement } if (ActiveDeviceRoles[i] == null) // Check if ActiveDeviceRole at current index is null { Console.WriteLine("{0} {1} Device = {2}", RoleName, RequestedDeviceType, "Not Set"); // Output info to event log } else { Console.WriteLine("{0} {1} Device = {2}", RoleName, RequestedDeviceType, ActiveDeviceRoles[i]); // Output info to event log } } } else { Console.WriteLine("No audio playback devices enabled"); // Output info to event log } } Console.ReadLine(); }