regKeyExists function

bool regKeyExists(
  1. HKEY hkey,
  2. String subKey
)

Tests if a registry key exists.

hkey is typically HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE

See the following link for additional values: https://docs.microsoft.com/en-us/windows/win32/sysinfo/predefined-keys

subKey is name of the registry key you want to open. This is typically something like 'Environment'.

A WindowsException is thrown the call falls.

Implementation

bool regKeyExists(HKEY hkey, String subKey) {
  var exists = false;
  final pOpenKey = calloc<Pointer>();
  final pSubKey = subKey.toNativeUtf16();

  try {
    final result = RegOpenKeyEx(
      hkey,
      PCWSTR(pSubKey),
      0,
      KEY_QUERY_VALUE,
      pOpenKey,
    );
    if (result == ERROR_SUCCESS) {
      exists = true;
      HKEY(pOpenKey.value).close();
    }
  } finally {
    calloc
      ..free(pOpenKey)
      ..free(pSubKey);
  }
  return exists;
}