What is the usage of regopenkeyex in C++?

In C++, the function RegOpenKeyEx is used to open a specific registry key and returns a handle for further operations.

The function prototype is as follows:

LONG RegOpenKeyEx(
  HKEY    hKey,
  LPCTSTR lpSubKey,
  DWORD   ulOptions,
  REGSAM  samDesired,
  PHKEY   phkResult
);

Explanation of parameters:

  1. hKey: Parent handle of the registry item to be opened. It can be one of the following pre-defined root keys: HKEY_CLASSES_ROOT, HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS, etc.
  2. lpSubKey: A relative path string to the registry key to be opened, which can be NULL or an empty string.
  3. ulOptions: Open options, can be either 0 or REG_OPTION_OPEN_LINK. Typically use 0.
  4. samDesired: Access permissions, specifying access rights to registry keys. Common permission flags include KEY_ALL_ACCESS, KEY_READ, and KEY_WRITE.
  5. phkResult: Receive the handle of the open registry key.

return value:

  1. Return ERROR_SUCCESS upon success. If the function fails, return an error code.

Example of use:

#include <Windows.h>
#include <iostream>

int main() {
    HKEY hKey;
    DWORD dwDisposition;

    // 打开HKEY_CURRENT_USER下的某个子项
    LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_ALL_ACCESS, &hKey);
    if (result != ERROR_SUCCESS) {
        std::cout << "Failed to open key. Error code: " << result << std::endl;
        return 1;
    }

    // 使用hKey进行后续操作,如读取或写入键值

    // 关闭注册表项句柄
    RegCloseKey(hKey);

    return 0;
}

In the above example, we opened a subkey under HKEY_CURRENT_USER and then used the returned handle for further reading or writing operations. Finally, we closed the registry key handle to release resources.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds