Windows读写注册表的例子

在MSDN中,有个读写注册表的例子,很有参考价值。拷贝在这里:

说明部分:

Platform SDK: Debugging and Error Handling
Adding a Source to the Registry
You can use the default Application log without adding an event source to the registry. However, Event Viewer will not be able to map your event identifier codes to message strings unless you register your event source and provide a message file. For more information, see Message Files.

You can add a new source name to the registry by opening a new registry subkey under the Application key or a custom log using the RegCreateKeyEx function, and adding registry values to the new subkey using the RegSetValueEx function. The following example opens a new source and adds a message-file name and a bitmask of supported types.

下面是MSDN给的代码:

BOOL AddEventSource(
   LPTSTR pszLogName, // Application log or a custom log
   LPTSTR pszSrcName, // event source name
   LPTSTR pszMsgDLL,  // path for message DLL
   DWORD  dwNum)      // number of categories
{
   HKEY hk; 
   DWORD dwData, dwDisp; 
   TCHAR szBuf[MAX_PATH]; 

   // Create the event source as a subkey of the log. 

   wsprintf(szBuf, 
      "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s",
      pszLogName, pszSrcName); 

   if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szBuf, 
          0, NULL, REG_OPTION_NON_VOLATILE,
          KEY_WRITE, NULL, &hk, &dwDisp)) 
   {
      printf("Could not create the registry key."); 
      return FALSE;
   }

   // Set the name of the message file. 

   if (RegSetValueEx(hk,              // subkey handle 
           "EventMessageFile",        // value name 
           0,                         // must be zero 
           REG_EXPAND_SZ,             // value type 
           (LPBYTE) pszMsgDLL,        // pointer to value data 
           (DWORD) lstrlen(pszMsgDLL)+1)) // length of value data 
   {
      printf("Could not set the event message file."); 
      RegCloseKey(hk); 
      return FALSE;
   }

   // Set the supported event types. 

   dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | 
        EVENTLOG_INFORMATION_TYPE; 

   if (RegSetValueEx(hk,      // subkey handle 
           "TypesSupported",  // value name 
           0,                 // must be zero 
           REG_DWORD,         // value type 
           (LPBYTE) &dwData,  // pointer to value data 
           sizeof(DWORD)))    // length of value data 
   {
      printf("Could not set the supported types."); 
      RegCloseKey(hk); 
      return FALSE;
   }

   // Set the category message file and number of categories.

   if (RegSetValueEx(hk,              // subkey handle 
           "CategoryMessageFile",     // value name 
           0,                         // must be zero 
           REG_EXPAND_SZ,             // value type 
           (LPBYTE) pszMsgDLL,        // pointer to value data 
           (DWORD) lstrlen(pszMsgDLL)+1)) // length of value data 
   {
      printf("Could not set the category message file."); 
      RegCloseKey(hk); 
      return FALSE;
   }

   if (RegSetValueEx(hk,      // subkey handle 
           "CategoryCount",   // value name 
           0,                 // must be zero 
           REG_DWORD,         // value type 
           (LPBYTE) &dwNum,   // pointer to value data 
           sizeof(DWORD)))    // length of value data 
   {
      printf("Could not set the category count."); 
      RegCloseKey(hk); 
      return FALSE;
   }

   RegCloseKey(hk); 
   return TRUE;
}

在MSDN的这个例子上,自己又写了下面的例子进行演练,用的是Windows Application类型。为了简化,class的声明&定义都放在cpp文件中了。

#include <windows.h>

class RegHelper {
public:
    RegHelper();
    ~RegHelper();

    BOOL Open();
    BOOL Query(DWORD &value);
    BOOL Update(DWORD value);

private:
    CHAR* GetLastErrorText(DWORD errorCode);

private:
    enum {DEFAULT_VALUE = 100};
    HKEY m_hRootKey;
    HKEY m_hTargetKey;
    LPCTSTR m_szTargetKey;
    LPCTSTR m_szItemName;
};

RegHelper::RegHelper()
{
    m_hRootKey = HKEY_LOCAL_MACHINE;
    m_hTargetKey = NULL;
    m_szTargetKey = "Software\\Microsoft\\Windows\\CurrentVersion\\here_is_my_keys";
    m_szItemName = "Number";
}

RegHelper::~RegHelper()
{
    if (m_hTargetKey) RegCloseKey(m_hTargetKey);
}

BOOL RegHelper::Open()
{   
    DWORD dwDisposition;

    DWORD dwErrorCode = RegCreateKeyEx(HKEY_LOCAL_MACHINE, m_szTargetKey,
        0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &m_hTargetKey, &dwDisposition);

    if (ERROR_SUCCESS != dwErrorCode) {
        printf("%s\n", GetLastErrorText(dwErrorCode));
        m_hTargetKey = NULL;
        return FALSE;
    }

    if (dwDisposition == REG_CREATED_NEW_KEY) Update(DEFAULT_VALUE);

    return TRUE;
}

BOOL RegHelper::Query(DWORD &value)
{
    if (NULL == m_hTargetKey) return FALSE;

    DWORD dwType;
    DWORD len;
    DWORD dwErrorCode = RegQueryValueEx(m_hTargetKey, m_szItemName, NULL, &dwType,
        (LPBYTE)&value, &len);
    if (dwErrorCode != ERROR_SUCCESS) {
        printf("%s\n", GetLastErrorText(dwErrorCode));
        return FALSE;
    }

    return dwType != REG_DWORD;
}

BOOL RegHelper::Update(DWORD value)
{
    if (NULL == m_hTargetKey) return FALSE;

    DWORD dwErrorCode = RegSetValueEx(m_hTargetKey,
       m_szItemName,
       0,
       REG_DWORD,
       (LPBYTE) &value,
       sizeof(DWORD));

    if (dwErrorCode != ERROR_SUCCESS) {
        printf("%s\n", GetLastErrorText(dwErrorCode));
        return FALSE;
    }

    return TRUE;
}


CHAR* RegHelper::GetLastErrorText(DWORD errorCode) {
    static CHAR pBuf[1024] = { 0 };
    const ULONG bufSize = 1024;
    DWORD retSize;
    LPTSTR pTemp = NULL;

    pBuf[0] = '0';

    retSize = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_ARGUMENT_ARRAY,
        NULL,
        errorCode,
        LANG_NEUTRAL,
        (LPTSTR)&pTemp,
        0,
        NULL);
    if (retSize > 0) {
        pTemp[strlen(pTemp) - 2] = '\0'; //remove cr and newline character
        sprintf(pBuf, "%0.*s", bufSize, pTemp);
        LocalFree((HLOCAL)pTemp);
    }

    return(pBuf);
}

int main(int argc, char* argv[])
{
    RegHelper helper;
    if (!helper.Open()) return 1;

    DWORD value;
    helper.Query(value); // TODO exception ...
    printf("value: %d\n", value);

    value++;
    if (!helper.Update(value)) {
        printf("Update failed.\n");
        return 1;
    }

    helper.Query(value);
    printf("value: %d\n", value);

    return 0;
}

其中获取错误码对应上一篇文档:
Windows开发常用的获取错误码对应文本的例子

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值