Compartir a través de


ManagementEventWatcher Constructores

Definición

Inicializa una nueva instancia de la clase ManagementEventWatcher.

Sobrecargas

ManagementEventWatcher()

Inicializa una nueva instancia de la clase ManagementEventWatcher. Para una posterior inicialización, establezca las propiedades del objeto. Este es el constructor sin parámetros.

ManagementEventWatcher(EventQuery)

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI.

ManagementEventWatcher(String)

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI en forma de cadena.

ManagementEventWatcher(ManagementScope, EventQuery)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada.

ManagementEventWatcher(String, String)

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada. Para esta variante, la consulta y el ámbito se especifican como cadenas.

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. Para esta variante, la consulta y el ámbito son objetos especificados. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.

ManagementEventWatcher(String, String, EventWatcherOptions)

Inicializa una nueva instancia de la ManagementEventWatcher clase que escucha eventos conformes a la consulta de eventos WMI especificada, según las opciones especificadas. Para esta variante, la consulta y el ámbito se especifican como cadenas. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.

ManagementEventWatcher()

Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs

Inicializa una nueva instancia de la clase ManagementEventWatcher. Para una posterior inicialización, establezca las propiedades del objeto. Este es el constructor sin parámetros.

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

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque la clase de eventos está __InstanceCreationEvent. Para obtener más información, consulte la documentación de Instrumental de administración de Windows . El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.

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

Plena confianza para el llamador inmediato. Un código de confianza parcial no puede utilizar este miembro. Para obtener más información, consulte Uso de bibliotecas de código de confianza parcial.

Se aplica a

ManagementEventWatcher(EventQuery)

Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI.

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.

Ejemplos

En este ejemplo de código, el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque la clase de eventos está __InstanceCreationEvent. Para obtener más información, consulte la documentación de Instrumental de administración de Windows . El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.

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 escuchará eventos es el espacio de nombres predeterminado que está establecido actualmente.

Seguridad de .NET Framework

Plena confianza para el llamador inmediato. Un código de confianza parcial no puede utilizar este miembro. Para obtener más información, consulte Uso de bibliotecas de código de confianza parcial.

Se aplica a

ManagementEventWatcher(String)

Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs

Inicializa una nueva instancia de la clase ManagementEventWatcher cuando se proporciona una consulta de eventos WMI en forma de cadena.

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.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque la clase de eventos está __InstanceCreationEvent. Para obtener más información, consulte la documentación de Instrumental de administración de Windows . El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.

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 escuchará eventos es el espacio de nombres predeterminado que está establecido actualmente.

Seguridad de .NET Framework

Plena confianza para el llamador inmediato. Un código de confianza parcial no puede utilizar este miembro. Para obtener más información, consulte Uso de bibliotecas de código de confianza parcial.

Se aplica a

ManagementEventWatcher(ManagementScope, EventQuery)

Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada.

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.

query
EventQuery

EventQuery que representa una consulta de eventos WMI, la cual determina los eventos que escuchará el monitor.

Ejemplos

En este ejemplo de código, el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque la clase de eventos está __InstanceCreationEvent. Para obtener más información, consulte la documentación de Instrumental de administración de Windows . El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.

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

Plena confianza para el llamador inmediato. Un código de confianza parcial no puede utilizar este miembro. Para obtener más información, consulte Uso de bibliotecas de código de confianza parcial.

Se aplica a

ManagementEventWatcher(String, String)

Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs

Inicializa una nueva instancia de la clase ManagementEventWatcher que escucha los eventos de acuerdo con la consulta de eventos WMI dada. Para esta variante, la consulta y el ámbito se especifican como cadenas.

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.

query
String

Consulta que define los eventos que escuchará el monitor.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque la clase de eventos está __InstanceCreationEvent. Para obtener más información, consulte la documentación de Instrumental de administración de Windows . El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.

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

Plena confianza para el llamador inmediato. Un código de confianza parcial no puede utilizar este miembro. Para obtener más información, consulte Uso de bibliotecas de código de confianza parcial.

Se aplica a

ManagementEventWatcher(ManagementScope, EventQuery, EventWatcherOptions)

Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs

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. Para esta variante, la consulta y el ámbito son objetos especificados. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.

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.

query
EventQuery

EventQuery que representa una consulta de eventos WMI, la cual determina los eventos que escuchará el monitor.

options
EventWatcherOptions

EventWatcherOptions que representa las opciones adicionales utilizadas para inspeccionar los eventos.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque la clase de eventos está __InstanceCreationEvent. Para obtener más información, consulte la documentación de Instrumental de administración de Windows . El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.

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

Plena confianza para el llamador inmediato. Un código de confianza parcial no puede utilizar este miembro. Para obtener más información, consulte Uso de bibliotecas de código de confianza parcial.

Se aplica a

ManagementEventWatcher(String, String, EventWatcherOptions)

Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs
Source:
ManagementEventWatcher.cs

Inicializa una nueva instancia de la ManagementEventWatcher clase que escucha eventos conformes a la consulta de eventos WMI especificada, según las opciones especificadas. Para esta variante, la consulta y el ámbito se especifican como cadenas. El objeto de opciones puede especificar opciones como un tiempo de espera e información del contexto.

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.

query
String

Consulta que define los eventos que escuchará el monitor.

options
EventWatcherOptions

EventWatcherOptions que representa las opciones adicionales utilizadas para inspeccionar los eventos.

Ejemplos

En el ejemplo siguiente se muestra cómo el cliente recibe una notificación cuando se crea una instancia de Win32_Process porque la clase de eventos está __InstanceCreationEvent. Para obtener más información, consulte la documentación de Instrumental de administración de Windows . El cliente recibe eventos de forma sincrónica tras llamar al método WaitForNextEvent. Para probar este ejemplo, inicie un proceso, como Bloc de notas, mientras se ejecuta el código de ejemplo.

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

Plena confianza para el llamador inmediato. Un código de confianza parcial no puede utilizar este miembro. Para obtener más información, consulte Uso de bibliotecas de código de confianza parcial.

Se aplica a