ManagementEventWatcher Constructores

Definición

Inicializa una nueva instancia de la clase ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class.

Sobrecargas

ManagementEventWatcher()

Inicializa una nueva instancia de la clase ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class. Para una posterior inicialización, establezca las propiedades del objeto.For further initialization, set the properties on the object. Este es el constructor sin parámetros.This is the parameterless constructor.

ManagementEventWatcher(EventQuery)

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query.

ManagementEventWatcher(String)

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI en forma de cadena.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query in the form of a string.

ManagementEventWatcher(ManagementScope, EventQuery)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query.

ManagementEventWatcher(String, String)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query. Para esta variante, la consulta y el ámbito se especifican como cadenas.For this variant, the query and the scope are specified as strings.

ManagementEventWatcher(ManagementScope, EventQuery, EventWatcherOptions)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada y las opciones especificadas.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Para esta variante, la consulta y el ámbito son objetos especificados.For this variant, the query and the scope are specified objects. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.The options object can specify options such as time-out and context information.

ManagementEventWatcher(String, String, EventWatcherOptions)

Inicializa una nueva instancia de la ManagementEventWatcher clase que escucha los eventos que se ajustan a la consulta de eventos WMI dada, de acuerdo con las opciones especificadas.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Para esta variante, la consulta y el ámbito se especifican como cadenas.For this variant, the query and the scope are specified as strings. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.The options object can specify options such as a time-out and context information.

ManagementEventWatcher()

Inicializa una nueva instancia de la clase ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class. Para una posterior inicialización, establezca las propiedades del objeto.For further initialization, set the properties on the object. Este es el constructor sin parámetros.This is the parameterless constructor.

public:
 ManagementEventWatcher();
public ManagementEventWatcher ();
Public Sub New ()

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe la notificación cuando se crea una instancia de Win32_Process porque se __InstanceCreationEvent la clase de eventos.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obtener más información, consulte la documentación de instrumental de administración de Windows .For more information, see the Windows Management Instrumentation documentation. El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.This example can be tested by starting a process, such as Notepad, while the example code is running.

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 change in a service
        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();
        watcher.Query = 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;
    }
}
Imports System.Management

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

Public Class EventWatcherPolling
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Create event query to be notified within 1 second of 
        ' a change in a service
        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
        watcher.Query = 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

Comentarios

Seguridad de .NET Framework.NET Framework Security

Plena confianza para el llamador inmediato.Full trust for the immediate caller. Un código de confianza parcial no puede utilizar este miembro.This member cannot be used by partially trusted code. Para obtener más información, vea usar bibliotecas desde código de confianza parcial.For more information, see Using Libraries from Partially Trusted Code.

Se aplica a

ManagementEventWatcher(EventQuery)

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query.

public:
 ManagementEventWatcher(System::Management::EventQuery ^ query);
public ManagementEventWatcher (System.Management.EventQuery query);
new System.Management.ManagementEventWatcher : System.Management.EventQuery -> System.Management.ManagementEventWatcher
Public Sub New (query As EventQuery)

Parámetros

query
EventQuery

EventQuery que representa una consulta de eventos WMI, la cual determina los eventos que escuchará el monitor.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

Ejemplos

En este ejemplo de código, el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque se __InstanceCreationEvent la clase de eventos.In this code example, the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obtener más información, consulte la documentación de instrumental de administración de Windows .For more information, see the Windows Management Instrumentation documentation. El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.This example can be tested by starting a process, such as Notepad, while the example code is running.

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 change in a service
        string query =
            "SELECT * FROM __InstanceCreationEvent "
            + "WITHIN 1 WHERE " +
            "TargetInstance isa \"Win32_Process\"";

        // Initialize an event watcher and subscribe to events
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher(new EventQuery(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;
    }
}
Imports System.Management

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

Public Class EventWatcherPolling
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Create event query to be notified within 1 second of 
        ' a change in a service
        Dim query As String
        query = "SELECT * FROM __InstanceCreationEvent " _
            & "WITHIN 1 WHERE " & _
            "TargetInstance isa ""Win32_Process"""

        ' Initialize an event watcher and subscribe to events 
        ' that match this query
        Dim watcher As New ManagementEventWatcher(New EventQuery( _
        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

Comentarios

El espacio de nombres en el que el monitor va a escuchar eventos es el espacio de nombres predeterminado que está establecido actualmente.The namespace in which the watcher will be listening for events is the default namespace that is currently set.

Seguridad de .NET Framework.NET Framework Security

Plena confianza para el llamador inmediato.Full trust for the immediate caller. Un código de confianza parcial no puede utilizar este miembro.This member cannot be used by partially trusted code. Para obtener más información, vea usar bibliotecas desde código de confianza parcial.For more information, see Using Libraries from Partially Trusted Code.

Se aplica a

ManagementEventWatcher(String)

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI en forma de cadena.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query in the form of a string.

public:
 ManagementEventWatcher(System::String ^ query);
public ManagementEventWatcher (string query);
new System.Management.ManagementEventWatcher : string -> System.Management.ManagementEventWatcher
Public Sub New (query As String)

Parámetros

query
String

Consulta de eventos WMI, que define los eventos que escuchará el monitor.A WMI event query, which defines the events for which the watcher will listen.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe la notificación cuando se crea una instancia de Win32_Process porque se __InstanceCreationEvent la clase de eventos.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obtener más información, consulte la documentación de instrumental de administración de Windows .For more information, see the Windows Management Instrumentation documentation. El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.This example can be tested by starting a process, such as Notepad, while the example code is running.

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 change in a service
        string query =
            "SELECT * FROM __InstanceCreationEvent "
            + "WITHIN 1 WHERE " +
            "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;
    }
}
Imports System.Management

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

Public Class EventWatcherPolling
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Create event query to be notified within 1 second of 
        ' a change in a service
        Dim query As String
        query = "SELECT * FROM __InstanceCreationEvent " _
            & "WITHIN 1 WHERE " & _
            "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

Comentarios

El espacio de nombres en el que el monitor va a escuchar eventos es el espacio de nombres predeterminado que está establecido actualmente.The namespace in which the watcher will be listening for events is the default namespace that is currently set.

Seguridad de .NET Framework.NET Framework Security

Plena confianza para el llamador inmediato.Full trust for the immediate caller. Un código de confianza parcial no puede utilizar este miembro.This member cannot be used by partially trusted code. Para obtener más información, vea usar bibliotecas desde código de confianza parcial.For more information, see Using Libraries from Partially Trusted Code.

Se aplica a

ManagementEventWatcher(ManagementScope, EventQuery)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query.

public:
 ManagementEventWatcher(System::Management::ManagementScope ^ scope, System::Management::EventQuery ^ query);
public ManagementEventWatcher (System.Management.ManagementScope scope, System.Management.EventQuery query);
new System.Management.ManagementEventWatcher : System.Management.ManagementScope * System.Management.EventQuery -> System.Management.ManagementEventWatcher
Public Sub New (scope As ManagementScope, query As EventQuery)

Parámetros

scope
ManagementScope

ManagementScope que representa el ámbito (espacio de nombres) donde el monitor escuchará los eventos.A ManagementScope representing the scope (namespace) in which the watcher will listen for events.

query
EventQuery

EventQuery que representa una consulta de eventos WMI, la cual determina los eventos que escuchará el monitor.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

Ejemplos

En este ejemplo de código, el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque se __InstanceCreationEvent la clase de eventos.In this code example, the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obtener más información, consulte la documentación de instrumental de administración de Windows .For more information, see the Windows Management Instrumentation documentation. El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.This example can be tested by starting a process, such as Notepad, while the example code is running.

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 change in a service
        string query =
            "SELECT * FROM __InstanceCreationEvent "
            + "WITHIN 1 WHERE " +
            "TargetInstance isa \"Win32_Process\"";

        // Initialize an event watcher and subscribe to events
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher(
            new ManagementScope("root\\CIMV2"),
            new EventQuery(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;
    }
}
Imports System.Management

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

Public Class EventWatcherPolling
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Create event query to be notified within 1 second of 
        ' a change in a service
        Dim query As String
        query = "SELECT * FROM __InstanceCreationEvent " _
            & "WITHIN 1 WHERE " & _
            "TargetInstance isa ""Win32_Process"""

        ' Initialize an event watcher and subscribe to events 
        ' that match this query
        Dim watcher As New ManagementEventWatcher( _
            New ManagementScope("root\CIMV2"), _
            New EventQuery(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

Comentarios

Seguridad de .NET Framework.NET Framework Security

Plena confianza para el llamador inmediato.Full trust for the immediate caller. Un código de confianza parcial no puede utilizar este miembro.This member cannot be used by partially trusted code. Para obtener más información, vea usar bibliotecas desde código de confianza parcial.For more information, see Using Libraries from Partially Trusted Code.

Se aplica a

ManagementEventWatcher(String, String)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query. Para esta variante, la consulta y el ámbito se especifican como cadenas.For this variant, the query and the scope are specified as strings.

public:
 ManagementEventWatcher(System::String ^ scope, System::String ^ query);
public ManagementEventWatcher (string scope, string query);
new System.Management.ManagementEventWatcher : string * string -> System.Management.ManagementEventWatcher
Public Sub New (scope As String, query As String)

Parámetros

scope
String

Ámbito de administración (espacio de nombres) donde el monitor escuchará los eventos.The management scope (namespace) in which the watcher will listen for events.

query
String

Consulta que define los eventos que escuchará el monitor.The query that defines the events for which the watcher will listen.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe la notificación cuando se crea una instancia de Win32_Process porque se __InstanceCreationEvent la clase de eventos.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obtener más información, consulte la documentación de instrumental de administración de Windows .For more information, see the Windows Management Instrumentation documentation. El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.This example can be tested by starting a process, such as Notepad, while the example code is running.

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 change in a service
        string query =
            "SELECT * FROM __InstanceCreationEvent "
            + "WITHIN 1 WHERE " +
            "TargetInstance isa \"Win32_Process\"";

        // Initialize an event watcher and subscribe to events
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher("root\\CIMV2",
            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;
    }
}
Imports System.Management

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

Public Class EventWatcherPolling
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Create event query to be notified within 1 second of 
        ' a change in a service
        Dim query As String
        query = "SELECT * FROM __InstanceCreationEvent " _
            & "WITHIN 1 WHERE " & _
            "TargetInstance isa ""Win32_Process"""

        ' Initialize an event watcher and subscribe to events 
        ' that match this query
        Dim watcher As New ManagementEventWatcher( _
            "root\CIMV2", 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

Comentarios

Seguridad de .NET Framework.NET Framework Security

Plena confianza para el llamador inmediato.Full trust for the immediate caller. Un código de confianza parcial no puede utilizar este miembro.This member cannot be used by partially trusted code. Para obtener más información, vea usar bibliotecas desde código de confianza parcial.For more information, see Using Libraries from Partially Trusted Code.

Se aplica a

ManagementEventWatcher(ManagementScope, EventQuery, EventWatcherOptions)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada y las opciones especificadas.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Para esta variante, la consulta y el ámbito son objetos especificados.For this variant, the query and the scope are specified objects. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.The options object can specify options such as time-out and context information.

public:
 ManagementEventWatcher(System::Management::ManagementScope ^ scope, System::Management::EventQuery ^ query, System::Management::EventWatcherOptions ^ options);
public ManagementEventWatcher (System.Management.ManagementScope scope, System.Management.EventQuery query, System.Management.EventWatcherOptions options);
new System.Management.ManagementEventWatcher : System.Management.ManagementScope * System.Management.EventQuery * System.Management.EventWatcherOptions -> System.Management.ManagementEventWatcher
Public Sub New (scope As ManagementScope, query As EventQuery, options As EventWatcherOptions)

Parámetros

scope
ManagementScope

ManagementScope que representa el ámbito (espacio de nombres) donde el monitor escuchará los eventos.A ManagementScope representing the scope (namespace) in which the watcher will listen for events.

query
EventQuery

EventQuery que representa una consulta de eventos WMI, la cual determina los eventos que escuchará el monitor.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

options
EventWatcherOptions

EventWatcherOptions que representa las opciones adicionales utilizadas para inspeccionar los eventos.An EventWatcherOptions representing additional options used to watch for events.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe la notificación cuando se crea una instancia de Win32_Process porque se __InstanceCreationEvent la clase de eventos.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obtener más información, consulte la documentación de instrumental de administración de Windows .For more information, see the Windows Management Instrumentation documentation. El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.This example can be tested by starting a process, such as Notepad, while the example code is running.

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 change in a service
        string query =
            "SELECT * FROM __InstanceCreationEvent "
            + "WITHIN 1 WHERE " +
            "TargetInstance isa \"Win32_Process\"";

        // Event options
        // blockSize = 1, so wait for 1 event to return
        EventWatcherOptions options = new EventWatcherOptions(
            null, TimeSpan.MaxValue, 1);

        // Initialize an event watcher and subscribe to events
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher(
            new ManagementScope("root\\CIMV2"),
            new EventQuery(query), options);

        // 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;
    }
}
Imports System.Management

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

Public Class EventWatcherPolling
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Create event query to be notified within 1 second of 
        ' a change in a service
        Dim query As String
        query = "SELECT * FROM __InstanceCreationEvent " _
            & "WITHIN 1 WHERE " & _
            "TargetInstance isa ""Win32_Process"""

        ' Event options
        ' blockSize = 1, so wait for 1 event to return
        Dim options As New EventWatcherOptions( _
            Nothing, TimeSpan.MaxValue, 1)


        ' Initialize an event watcher and subscribe to events 
        ' that match this query
        Dim watcher As New ManagementEventWatcher( _
            New ManagementScope("root\CIMV2"), _
            New EventQuery(query), _
            options)

        ' 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

Comentarios

Seguridad de .NET Framework.NET Framework Security

Plena confianza para el llamador inmediato.Full trust for the immediate caller. Un código de confianza parcial no puede utilizar este miembro.This member cannot be used by partially trusted code. Para obtener más información, vea usar bibliotecas desde código de confianza parcial.For more information, see Using Libraries from Partially Trusted Code.

Se aplica a

ManagementEventWatcher(String, String, EventWatcherOptions)

Inicializa una nueva instancia de la ManagementEventWatcher clase que escucha los eventos que se ajustan a la consulta de eventos WMI dada, de acuerdo con las opciones especificadas.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Para esta variante, la consulta y el ámbito se especifican como cadenas.For this variant, the query and the scope are specified as strings. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.The options object can specify options such as a time-out and context information.

public:
 ManagementEventWatcher(System::String ^ scope, System::String ^ query, System::Management::EventWatcherOptions ^ options);
public ManagementEventWatcher (string scope, string query, System.Management.EventWatcherOptions options);
new System.Management.ManagementEventWatcher : string * string * System.Management.EventWatcherOptions -> System.Management.ManagementEventWatcher
Public Sub New (scope As String, query As String, options As EventWatcherOptions)

Parámetros

scope
String

Ámbito de administración (espacio de nombres) donde el monitor escuchará los eventos.The management scope (namespace) in which the watcher will listen for events.

query
String

Consulta que define los eventos que escuchará el monitor.The query that defines the events for which the watcher will listen.

options
EventWatcherOptions

EventWatcherOptions que representa las opciones adicionales utilizadas para inspeccionar los eventos.An EventWatcherOptions representing additional options used to watch for events.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe la notificación cuando se crea una instancia de Win32_Process porque se __InstanceCreationEvent la clase de eventos.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obtener más información, consulte la documentación de instrumental de administración de Windows .For more information, see the Windows Management Instrumentation documentation. El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.This example can be tested by starting a process, such as Notepad, while the example code is running.

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 change in a service
        string query =
            "SELECT * FROM __InstanceCreationEvent "
            + "WITHIN 1 WHERE " +
            "TargetInstance isa \"Win32_Process\"";

        // Event options
        // blockSize = 1, so wait for 1 event to return
        EventWatcherOptions options = new EventWatcherOptions(
            null, TimeSpan.MaxValue, 1);

        // Initialize an event watcher and subscribe to events
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher(
            new ManagementScope("root\\CIMV2"),
            new EventQuery(query), options);

        // 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;
    }
}
Imports System.Management

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

Public Class EventWatcherPolling
    Public Overloads Shared Function _
        Main(ByVal args() As String) As Integer

        ' Create event query to be notified within 1 second of 
        ' a change in a service
        Dim query As String
        query = "SELECT * FROM __InstanceCreationEvent " _
            & "WITHIN 1 WHERE " & _
            "TargetInstance isa ""Win32_Process"""

        ' Event options
        ' blockSize = 1, so wait for 1 event to return
        Dim options As New EventWatcherOptions( _
            Nothing, TimeSpan.MaxValue, 1)


        ' Initialize an event watcher and subscribe to events 
        ' that match this query
        Dim watcher As New ManagementEventWatcher( _
            "root\CIMV2", _
            query, _
            options)

        ' 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

Comentarios

Seguridad de .NET Framework.NET Framework Security

Plena confianza para el llamador inmediato.Full trust for the immediate caller. Un código de confianza parcial no puede utilizar este miembro.This member cannot be used by partially trusted code. Para obtener más información, vea usar bibliotecas desde código de confianza parcial.For more information, see Using Libraries from Partially Trusted Code.

Se aplica a