接收策略更改事件

LSA 提供了可用于在本地系统上发生策略更改时接收通知的函数。

若要接收通知,请通过调用 CreateEvent 函数创建新的事件对象,然后调用 LsaRegisterPolicyChangeNotification 函数。 然后,应用程序可以调用 WaitForSingleObjectWaitForSingleObjectExRegisterWaitForSingleObject 等等待事件发生。 当事件发生或超时期限到期时,wait 函数将返回 。 通常,通知事件在多线程应用程序中使用,其中一个线程等待事件,而其他线程继续处理。

当应用程序不再需要接收通知时,它应调用 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);
}

有关事件对象、等待函数和同步的详细信息,请参阅 使用事件对象