In fact, the problem was that on laptops (PCs with serial ports, such as COM1 port) the first time you run the SERIALCOMM folder that was not created in the registry, because
we basically connected the device to a USB port or a serial port created by the SERIALCOMM folder, in which case we use WMI to connect the connected communication ports from the registry.
some laptops do not have USB and serial ports connected. Therefore, the SERIALCOMM folder is not created. During this time, we gain access to this registry path and get an error.
so thereβs a solution,
try { string scopePath = @"\\.\root\default"; ManagementScope managementScope = new ManagementScope(scopePath); string subkey = "HARDWARE\\DEVICEMAP\\SERIALCOMM"; using (RegistryKey prodx = Registry.LocalMachine) { prodx.CreateSubKey(subkey); } WqlEventQuery query = new WqlEventQuery( "SELECT * FROM RegistryKeyChangeEvent WHERE " + "Hive = 'HKEY_LOCAL_MACHINE'" + @"AND KeyPath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'"); registryWatcher = new ManagementEventWatcher(managementScope, query); registryWatcher.EventArrived += new EventArrivedEventHandler(SerialCommRegistryUpdated); registryWatcher.Start(); } catch (Exception ex) { Console.WriteLine(ex.Message); if (registryWatcher != null) { registryWatcher.Stop(); } }
source share