接收原則變更事件

LSA 提供函式,您可以在本機系統上有原則變更時,用來接收通知。

若要接收通知,請呼叫 CreateEvent 函式來建立新的事件物件,然後呼叫 LsaRegisterPolicyChangeNotification 函式。 然後,您的應用程式可以呼叫WaitForSingleObject、WaitForSingleObjectExRegisterWaitForSingleObject等等候函式,以等候事件發生。 等候函式會在事件發生時或逾時期間到期時傳回。 一般而言,通知事件會用於多執行緒應用程式中,其中一個執行緒會等候事件,而其他執行緒會繼續處理。

當您的應用程式不再需要接收通知時,它應該呼叫 LsaUnregisterPolicyChangeNotification ,然後呼叫 CloseHandle 以釋放事件物件控制碼。

下列範例顯示當系統稽核原則變更時,單一線程應用程式如何接收通知事件。

#include <windows.h>
#include <stdio.h>

void WaitForPolicyChanges()
{
  HANDLE hEvent;
  NTSTATUS ntsResult;
  DWORD dwResult;

  // Create an event object.
  hEvent = CreateEvent( 
    NULL,  // child processes cannot inherit 
    FALSE, // automatically reset event
    FALSE, // start as a nonsignaled event
    NULL   // do not need a name
  );

  // Check that the event was created.
  if (hEvent == NULL) 
  {
    wprintf(L"Event object creation failed: %d\n",GetLastError());
    return;
  }
  // Register to receive auditing policy change notifications.
  ntsResult = LsaRegisterPolicyChangeNotification(
    PolicyNotifyAuditEventsInformation,
    hEvent
  );
  if (STATUS_SUCCESS != ntsResult)
  {
    wprintf(L"LsaRegisterPolicyChangeNotification failed.\n");
    CloseHandle(hEvent);
    return;
  }

  // Wait for the event to be triggered.
  dwResult = WaitForSingleObject( 
    hEvent, // handle to the event object
    300000  // time-out interval, in milliseconds
  );

  // The wait function returned.
  if (dwResult == WAIT_OBJECT_0)
  {  // received the notification signal
    wprintf(L"Notification received.\n");
  } 
  else 
  {  // received a time-out or error
    wprintf(L"Notification was not received.\n");
  }
  // Unregister for notification.
  LsaUnregisterPolicyChangeNotification(
    PolicyNotifyAuditEventsInformation,
    hEvent
  );

  // Free the event handle.
  CloseHandle(hEvent);
}

如需事件物件、等候函式和同步處理的詳細資訊,請參閱 使用事件物件