简体   繁体   English

检查注册表值是否存在Visual C ++ 2005

[英]Checking if Registry Value exists Visual C++ 2005

Im trying to code a Visual C++ 2005 routine that checks the registry for certain keys/values. 我试图编写一个Visual C ++ 2005例程来检查注册表中的某些键/值。 I have no trouble in writing code using c# but I need it in C++. 使用c#编写代码没有问题,但我需要用C ++编写代码。 Anybody know how to do this using c++ in vs2005. 任何人都知道如何在vs2005中使用c ++来做到这一点。

Many thanks Tony 非常感谢Tony

Here is some pseudo-code to retrieve the following: 这是一些用于检索以下内容的伪代码:

  1. If a registry key exists 如果存在注册表项
  2. What the default value is for that registry key 该注册表项的默认值是什么
  3. What a string value is 什么是字符串值
  4. What a DWORD value is 什么是DWORD值

Example code: 示例代码:

Include the library dependency: Advapi32.lib 包含库依赖项:Advapi32.lib

Put the following in your main or where you want to read the values: 将以下内容放在main中或要读取值的位置:

HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
bool bDoesNotExistsSpecifically (lres == ERROR_FILE_NOT_FOUND);
std::wstring strValueOfBinDir;
std::wstring strKeyDefaultValue;
GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");

Put these wrapper functions at the top of your code: 将这些包装函数放在代码的顶部:

LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
{
    nValue = nDefaultValue;
    DWORD dwBufferSize(sizeof(DWORD));
    DWORD nResult(0);
    LONG nError = ::RegQueryValueExW(hKey,
        strValueName.c_str(),
        0,
        NULL,
        reinterpret_cast<LPBYTE>(&nResult),
        &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        nValue = nResult;
    }
    return nError;
}


LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
{
    DWORD nDefValue((bDefaultValue) ? 1 : 0);
    DWORD nResult(nDefValue);
    LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
    if (ERROR_SUCCESS == nError)
    {
        bValue = (nResult != 0) ? true : false;
    }
    return nError;
}


LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
{
    strValue = strDefaultValue;
    WCHAR szBuffer[512];
    DWORD dwBufferSize = sizeof(szBuffer);
    ULONG nError;
    nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        strValue = szBuffer;
    }
    return nError;
}

There are Win32 APIs available: take a look at MSDN for RegOpenKey and friends (and the Registry Functions in general). 有可用的Win32 API:查看MSDN for RegOpenKey和朋友(以及一般的注册表功能 )。

Here is an example of 'Deleting a Key with Subkeys' . 以下是“使用子键删除密钥”的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM