Compartilhar via


RegistryNotifyCallback

Windows Mobile SupportedWindows Embedded CE Supported

9/8/2008

Essa função registra um temporário solicitação notificação. Ele é usado para solicitação que o chamador ser notificado por um callback especificado quando um valor especificado tiver sido alterado.

Syntax

HRESULT WINAPI RegistryNotifyCallback(
  HKEY hKey,
  LPCTSTR pszSubKey,
  LPCTSTR pszValueName,
  REGISTRYNOTIFYCALLBACK pfnRegistryNotifyCallback,
  DWORD dwUserData,
  NOTIFICATIONCONDITION * pCondition,
  HREGNOTIFY * phNotify
);

Parameters

  • hKey
    [no] Identificador para um atualmente aberto chave, ou um valor predefinido raiz.
  • pszSubKey
    [no] A chave sob a qual o valor é armazenado. Se esse valor é NULL, pszValueName é considerado em hKey.
  • pszValueName
    [no] O nome do valor no qual alteração notificações são solicitadas. Se esse valor é NULL, ele indica o valor usar como padrão.
  • dwUserData
    [no] Dados do usuário que serão passados voltar para o usuário com a notificação.
  • pfnRegistryNotifyCallback
    [no] Um ponteiro para uma função que será chamado voltar quando chega uma notificação. Para um protótipo para esta função, consulte REGISTRYNOTIFYCALLBACK.
  • pCondition
    [no] Condição que determina quando enviar a notificação. Quando a comparação entre pCondition o novo valor do Registro é TRUE e uma notificação será enviada. Se esse valor é NULL, qualquer alteração resulta em uma notificação.
  • phNotify
    [out] Recebe o identificador para a solicitação notificação. Esse identificador deve ser fechado usando RegistryCloseNotification Quando as notificações sobre essa chave não são mais necessários. Redefinir o dispositivo também pára a notificação.

Return Value

Valor Descrição

S_OK

A solicitação de notificação de alteração é registrado.

E_INVALIDARG

Inválido hKey, phNotify, Ou pfnRegistryNotifyCallback.

Um valor de erro retornado.

Valor de erro ajustada como um FACILITY_WIN32 HRESULT.

Remarks

O cliente irá ser notificado das alterações via o callback, que é executado no segmento particular separar a partir de segmento que chamado RegistryNotifyCallback.

Se o valor não existir no tempo do chamar para RegistryNotifyCallback, o cliente será notificado quando o valor é adicionado.

Para parar notificação e para fechar o identificador notificação, o chamador deve chamar RegistryCloseNotification. No entanto, esse tipo de notificação é temporário. Redefinir o dispositivo pára a notificação.

Esta função pode ser usada para monitor qualquer chave Registro no sistema. O snapi.h arquivo de cabeçalho contém definições para as chaves Registro, caminhos, valores e bitmasks para todas as notificações de de base que são fornecidas pelo sistema.

Se a notificação para o função callback falhar, a notificação será removida.

Se a chave especificada por hKey e pszSubKey Não existe, em seguida, hKey é monitorado até pszSubKey é criado, após o qual pszSubKey é monitorado e muda para a chave será notificações disparador conforme solicitado. Para minimizar a degradação desempenho possível proveniente de uma nuimber grande de subchaves que está sendo monitorado, ele é uma recomendação para transmitir (como hKey) o identificador para uma chave que é como fechar possíveis para pszSubKey Em vez de passar uma chave raiz. De exemplo, se o cliente é um jogo e ele for monitoração a chave estrutura HKEY_CURRENT_USER\... \MyCoolGame\Player1 e o jogo posteriormente criaria HKEY_CURRENT_USER\... \MyCoolGame\Player2, duas maneiras possíveis para notificação abordagem das alterações feitas a chave Player2 incluem:

Diminuição no desempenho em potencial Menos problemas potenciais

hKey = identificador para HKEY_CURRENT_USER epszSubKey= o caminho completo para Player2

hKey = identificador para HKEY_CURRENT_USER\... \MyCoolGame\ epszSubKey=Player2

Exemplo de código

O seguinte exemplo de código demonstra como usar RegistryNotifyCallback.

Observação

Para fazer o seguinte exemplo de código mais fácil de ler, verificação de segurança e manipulação de erro não estão incluídos.Esta exemplo de código não deve ser usado em uma configuração versão a menos que ele foi modificado para incluí-las.

void AdjustPowerConsumption(HREGNOTIFY hNotify, DWORD dwUserData, const PBYTE pData, const UINT cbData);
// Register to be notified of changes to the eighth bit
// in SN_POWERBATTERYSTATE_VALUE. The eighth bit is set to one when 
// the battery is critically low (and set to zero and when it is not).
HRESULT RegistryNotifyCallbackExample()
{
    NOTIFICATIONCONDITION nc;
    HRESULT hr         = S_OK;
    HREGNOTIFY hNotify = NULL;
    // Initialize the notification structure.
    // The mask for the eighth bit.
    nc.dwMask = 0x8;
    // Receive a notification whenever that bit toggles.
    nc.ctComparisonType = REG_CT_ANYCHANGE;
    // dw is ignored for REG_CT_ANYCHANGE.
    nc.TargetValue.dw = 0;
    
    hr = RegistryNotifyCallback(SN_POWERBATTERYSTATE_ROOT, 
                                SN_POWERBATTERYSTATE_PATH, 
                                SN_POWERBATTERYSTATE_VALUE, 
                                AdjustPowerConsumption, 
                                0, 
                                &nc, 
                                &hNotify);
    // Close the notification using RegistryCloseNotification when done.
    // Note that it is alright to call RegistryCloseNotification from the callback function.
    // hr = RegistryCloseNotification(hNotify);
    return hr;
}
// This is the callback function.
void AdjustPowerConsumption(HREGNOTIFY hNotify, DWORD dwUserData, const PBYTE pData, const UINT cbData)
{
    DWORD dwCritical;
    HRESULT hr = S_OK;
    // pData contains the new value for SN_POWERBATTERYSTATE_VALUE.
    dwCritical = (*(DWORD*) pData);
    // Extract the eighth bit.
    dwCritical = dwCritical & 0x8; 
critically low.
    {
 your statements for preserving energy, here.
    }
    // The battery level was critically low, but it is not now.
    else
    {
        // Add your statements for returning to the normal battery state, here.
    }
}

Exemplo de código

O seguinte exemplo de código demonstra como registrar temporário solicitações notificação para valores StatStore de telefone.

Observação

Para fazer o seguinte exemplo de código mais fácil de ler, verificação de segurança e manipulação de erro não estão incluídos.Esta exemplo de código não deve ser usado em uma configuração versão a menos que ele foi modificado para incluí-las.

#include <regext.h>
#include "snapi.h"
const TCHAR c_szPhoneRegistryRootkey[]      = TEXT("System\\State");
const TCHAR c_szPhoneRegistrySubkey[]       = TEXT("Phone");
const TCHAR c_szPhoneSignalStrength[]       = TEXT("Signal Strength");
const TCHAR c_szPhoneIncomingCallerNumber[] = TEXT("Incoming Caller Number");
const TCHAR c_szPhoneStatus[]               = TEXT("Status");
#define MAX_NOTIF 3
enum NotifType
{
      SignalStrength = 0,
      IncomingCallerNumber,
      PhoneRoaming
};
HREGNOTIFY g_hRegNotify[ MAX_NOTIF ] ;
// The call-back function for Registry Notifications.
void RegistryNotifyCallbackFunc(HREGNOTIFY hNotify, DWORD dwUserData, const PBYTE pData, const UINT cbData)
{
    TCHAR szOutput[MAX_PATH];
    // Identify the Notification received, based upon the User Data passed in, while registering for the notification.
    switch( dwUserData )
    {
        case SignalStrength:
            StringCchPrintf(szOutput, MAX_PATH, _T("The Signal Strength is %d"), (DWORD) *pData);
            break;
        case IncomingCallerNumber:
            StringCchPrintf(szOutput, MAX_PATH, _T("The Incoming Caller Number is %s"), (TCHAR*)pData);
            break;
        case PhoneRoaming:
            {
                  DWORD dw = 0;
                  // Copy the data sent to us into a local buffer.
                  memcpy(&dw, pData, cbData);
                  // Find out if the roaming status has been set by logically ANDing the data with the value 512 (the bitmask for roaming).
                  StringCchPrintf(szOutput, MAX_PATH, _T("The Roam Status of the Phone is %s"), ( dw & SN_PHONEROAMING_BITMASK ) == SN_PHONEROAMING_BITMASK  ? _T("TRUE") : _T("FALSE")  );
            }
            break;
        default :
            break;
    }
    OutputDebugString( szOutput );
    return;
}
void RegisterForPhoneNotifications()
{
    HKEY hKey;
    // Let us open the registry to get a handle to the Phone Registry key.
    if (S_OK == RegOpenKeyEx(HKEY_LOCAL_MACHINE, c_szPhoneRegistryRootkey, 0,  KEY_QUERY_VALUE, &hKey))
    {
    // Since we are registering for multiple notifications, let's pass some unique User Data for each notification ( 5th param ), 
    // which will help us identify the notification in the Call Back.
     // Let us register for Signal strength notifications.
     HRESULT hr = RegistryNotifyCallback(hKey, 
                                         c_szPhoneRegistrySubkey,
                                         c_szPhoneSignalStrength,
                                         RegistryNotifyCallbackFunc,
                                         SignalStrength,
                                         NULL,
                                         &g_hRegNotify[ SignalStrength ] );
        
    // Let us register for Incoming Caller Number notifications.
            hr = RegistryNotifyCallback(hKey, 
                                        c_szPhoneRegistrySubkey,
                                        c_szPhoneIncomingCallerNumber,
                                        RegistryNotifyCallbackFunc,
                                        IncomingCallerNumber,
                                        NULL,
                                        &g_hRegNotify [ IncomingCallerNumber ] );
    //  Let us register for Roaming status change notifications.
            hr = RegistryNotifyCallback(hKey, 
                                        c_szPhoneRegistrySubkey,
                                        c_szPhoneStatus,
                                        RegistryNotifyCallbackFunc,
                                        PhoneRoaming,
                                        NULL,
                                        &g_hRegNotify [ PhoneRoaming ] );
        RegCloseKey(hKey);
      
    }
}
void  CloseAllNotifications ()
{
     for (int i = 0; i < MAX_NOTIF; i++)
    {
            RegistryCloseNotification(g_hRegNotify[i]);
    }
}

Requirements

Header regext.h
Library aygshell.lib
Windows Embedded CE Windows Embedded CE 6.0 and later
Windows Mobile Pocket PC for Windows Mobile Version 5.0 and later, Smartphone for Windows Mobile Version 5.0 and later

See Also

Reference

REGISTRYNOTIFYCALLBACK Structure
RegistryBatchNotification
State and Notifications Broker Functions
State and Notifications Broker Reference

Concepts

Using the State and Notifications Broker in Native Code

Other Resources

State and Notifications Broker