How to: Receive an Event

Client applications can subscribe to receive events from an event-providing application by providing a query that describes the events and establishing a subscription through ManagementEventWatcher.

The client application can wait for an event by calling the System.Management.ManagementEventWatcher.WaitForNextEvent method, which establishes a synchronous subscription to receive events. Alternatively, the client may set up an asynchronous subscription and carry on other operations while waiting for events. For more information, see How to: Receive Management Events Without Waiting.

You create event queries with the EventQuery or WqlEventQuery classes. Both synchronous and asynchronous approaches produce temporary WMI event consumers. A temporary consumer does not resume running after a computer is restarted. For information on creating a permanent consumer, see "Receiving Events at All Times" in the Windows Management Instrumentation documentation in the MSDN Library.

For information on the underlying WMI event structure and available event classes, see "Receiving a WMI Event" in the Windows Management Instrumentation documentation in the MSDN Library. The use of WQL in WMI queries is described in "Querying with WQL" in the Windows Management Instrumentation documentation in the MSDN Library. The syntax reference for WQL is in "WQL (SQL for WMI)" in the Windows Management Instrumentation documentation in the MSDN Library.

Applications that provide events can use System.Management.Instrumentation namespace attribute classes to designate their event classes or derive a new event class from BaseEvent. For more information, see Providing Management Events.

To subscribe to events synchronously

  1. Specify an event query using an event query class, such as WqlEventQuery, which takes WQL query statements as input arguments to describe the event.

    WqlEventQuery query = 
              new WqlEventQuery("__InstanceCreationEvent", 
                 new TimeSpan(0,0,1), 
                 "TargetInstance isa \"Win32_Process\"");
    
  2. Create a new ManagementEventWatcher instance to establish the subscription.

    ManagementEventWatcher watcher = new ManagementEventWatcher(query);
    
  3. Wait for the events.

    ManagementBaseObject e = watcher.WaitForNextEvent();
    

Example

The following code example shows how to subscribe to WMI intrinsic events and receive them in a synchronous fashion. The example builds an event query in WQL syntax, uses it to initialize a ManagementEventWatcher object, and then waits for events that match the specified filter to be delivered.

In this code example, the client receives a notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. For more information, see "Win32_Process" and "__InstanceCreationEvent" in the Windows Management Instrumentation documentation in the MSDN Library. The client receives events synchronously by calling the System.Management.ManagementEventWatcher.WaitForNextEvent method. This example can be tested by starting a process, such as Notepad, while the example code is running.

Imports System
Imports System.Management

' This example shows synchronous consumption of events. 
' The client is blocked while waiting for events. 

Public Class EventWatcherPolling   
    Overloads Public Shared Function _
        Main(args() As String) As Integer
       
        ' Create event query to be notified within 1 second of 
        ' a process being created
        Dim query As New WqlEventQuery( _
            "__InstanceCreationEvent", _
            New TimeSpan(0, 0, 1), _
            "TargetInstance isa ""Win32_Process""")

        ' Initialize an event watcher and subscribe to events 
        ' that match this query
        Dim watcher As New ManagementEventWatcher(query)
        ' times watcher.WaitForNextEvent in 5 seconds
        watcher.Options.Timeout = New TimeSpan(0,0,5)  

        ' Block until the next event occurs 
        ' Note: this can be done in a loop
        ' if waiting for more than one occurrence
        Console.WriteLine( _
          "Open an application (notepad.exe) to trigger an event.")
        Dim e As ManagementBaseObject = _
            watcher.WaitForNextEvent()

        'Display information from the event
        Console.WriteLine( _
            "Process {0} has created, path is: {1}", _ 
            CType(e("TargetInstance"), _
                ManagementBaseObject)("Name"), _
            CType(e("TargetInstance"), _
                ManagementBaseObject)("ExecutablePath"))

        'Cancel the subscription
        watcher.Stop()
        Return 0

     End Function 'Main
End Class 'EventWatcherPolling
using System;
using System.Management;

// This example shows synchronous consumption of events. 
// The client is blocked while waiting for events. 

public class EventWatcherPolling 
{
    public static int Main(string[] args) 
    {
        // Create event query to be notified within 1 second of 
        // a new process being created
        WqlEventQuery query = 
            new WqlEventQuery("__InstanceCreationEvent", 
            new TimeSpan(0,0,1), 
            "TargetInstance isa \"Win32_Process\"");

        // Initialize an event watcher and subscribe to events 
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher(query);
        // times out watcher.WaitForNextEvent in 5 seconds
        watcher.Options.Timeout = new TimeSpan(0,0,5);
      
        // Block until the next event occurs 
        // Note: this can be done in a loop if waiting for 
        //        more than one occurrence
        Console.WriteLine(
          "Open an application (notepad.exe) to trigger an event.");
        ManagementBaseObject e = watcher.WaitForNextEvent();

        //Display information from the event
        Console.WriteLine(
            "Process {0} has been created, path is: {1}", 
            ((ManagementBaseObject)e
                ["TargetInstance"])["Name"],
            ((ManagementBaseObject)e
                ["TargetInstance"])["ExecutablePath"]);

        //Cancel the subscription
        watcher.Stop();
        return 0;
    }
}

Compiling the Code

See Also

Tasks

How to: Receive Management Events Without Waiting

Concepts

WMI Management Events

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.