ManagementEventWatcher Construtores

Definição

Inicializa uma nova instância da classe ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class.

Sobrecargas

ManagementEventWatcher()

Inicializa uma nova instância da classe ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class. Para inicialização adicional, defina as propriedades no objeto.For further initialization, set the properties on the object. Esse é o construtor sem parâmetros.This is the parameterless constructor.

ManagementEventWatcher(EventQuery)

Inicializa uma nova instância da classe ManagementEventWatcher ao receber uma consulta de evento WMI.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query.

ManagementEventWatcher(String)

Inicializa uma nova instância da classe ManagementEventWatcher quando é fornecida uma consulta de evento do WMI na forma de uma cadeia de caracteres.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query in the form of a string.

ManagementEventWatcher(ManagementScope, EventQuery)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a WMI a consulta de evento de WMI determinada.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query.

ManagementEventWatcher(String, String)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a WMI a consulta de evento de WMI determinada.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query. Para essa variante, a consulta e o escopo são especificados como cadeias de caracteres.For this variant, the query and the scope are specified as strings.

ManagementEventWatcher(ManagementScope, EventQuery, EventWatcherOptions)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a consulta de evento da WMI determinada, de acordo com as opções 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 essa variante, a consulta e o escopo são especificados como objetos.For this variant, the query and the scope are specified objects. O objeto de opções pode especificar opções, como informações de tempo limite e contexto.The options object can specify options such as time-out and context information.

ManagementEventWatcher(String, String, EventWatcherOptions)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a consulta de evento da WMI determinada, de acordo com as opções 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 essa variante, a consulta e o escopo são especificados como cadeias de caracteres.For this variant, the query and the scope are specified as strings. O objeto de opções pode especificar opções, como informações de tempo limite e contexto.The options object can specify options such as a time-out and context information.

ManagementEventWatcher()

Inicializa uma nova instância da classe ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class. Para inicialização adicional, defina as propriedades no objeto.For further initialization, set the properties on the object. Esse é o construtor sem parâmetros.This is the parameterless constructor.

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

Exemplos

O exemplo a seguir mostra como o cliente recebe a notificação quando uma instância do Win32_Process é criada porque a classe de evento é __InstanceCreationEvent.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obter mais informações, consulte a documentação do Instrumentação de gerenciamento do Windows .For more information, see the Windows Management Instrumentation documentation. O cliente recebe eventos de forma síncrona chamando o método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Este exemplo pode ser testado com o início de um processo, como o bloco de notas, enquanto o código de exemplo está em execução.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

Comentários

Segurança do .NET Framework.NET Framework Security

Confiança total para o chamador imediato.Full trust for the immediate caller. Este membro não pode ser usado pelo código parcialmente confiável.This member cannot be used by partially trusted code. Para obter mais informações, consulte usando bibliotecas de código parcialmente confiável.For more information, see Using Libraries from Partially Trusted Code.

ManagementEventWatcher(EventQuery)

Inicializa uma nova instância da classe ManagementEventWatcher ao receber uma consulta de evento 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

Um EventQuery que representa uma consulta de evento WMI, que determina os eventos para os quais o inspetor vai escutar.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

Exemplos

Neste exemplo de código, o cliente recebe a notificação quando uma instância de Win32_Process é criada porque a classe de evento é __InstanceCreationEvent.In this code example, the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obter mais informações, consulte a documentação do Instrumentação de gerenciamento do Windows .For more information, see the Windows Management Instrumentation documentation. O cliente recebe eventos de forma síncrona chamando o método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Este exemplo pode ser testado com o início de um processo, como o bloco de notas, enquanto o código de exemplo está em execução.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

Comentários

O namespace no qual o inspetor escutará eventos é o namespace padrão definido atualmente.The namespace in which the watcher will be listening for events is the default namespace that is currently set.

Segurança do .NET Framework.NET Framework Security

Confiança total para o chamador imediato.Full trust for the immediate caller. Este membro não pode ser usado pelo código parcialmente confiável.This member cannot be used by partially trusted code. Para obter mais informações, consulte usando bibliotecas de código parcialmente confiável.For more information, see Using Libraries from Partially Trusted Code.

ManagementEventWatcher(String)

Inicializa uma nova instância da classe ManagementEventWatcher quando é fornecida uma consulta de evento do WMI na forma de uma cadeia de caracteres.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

Uma consulta de evento WMI, que define os eventos para os quais o inspetor escutará.A WMI event query, which defines the events for which the watcher will listen.

Exemplos

O exemplo a seguir mostra como o cliente recebe a notificação quando uma instância do Win32_Process é criada porque a classe de evento é __InstanceCreationEvent.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obter mais informações, consulte a documentação do Instrumentação de gerenciamento do Windows .For more information, see the Windows Management Instrumentation documentation. O cliente recebe eventos de forma síncrona chamando o método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Este exemplo pode ser testado com o início de um processo, como o bloco de notas, enquanto o código de exemplo está em execução.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

Comentários

O namespace no qual o inspetor escutará eventos é o namespace padrão definido atualmente.The namespace in which the watcher will be listening for events is the default namespace that is currently set.

Segurança do .NET Framework.NET Framework Security

Confiança total para o chamador imediato.Full trust for the immediate caller. Este membro não pode ser usado pelo código parcialmente confiável.This member cannot be used by partially trusted code. Para obter mais informações, consulte usando bibliotecas de código parcialmente confiável.For more information, see Using Libraries from Partially Trusted Code.

ManagementEventWatcher(ManagementScope, EventQuery)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a WMI a consulta de evento de WMI determinada.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

Um ManagementScope que representa o escopo (namespace) em que o inspetor escutará eventos.A ManagementScope representing the scope (namespace) in which the watcher will listen for events.

query
EventQuery

Um EventQuery que representa uma consulta de evento WMI, que determina os eventos para os quais o inspetor vai escutar.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

Exemplos

Neste exemplo de código, o cliente recebe a notificação quando uma instância de Win32_Process é criada porque a classe de evento é __InstanceCreationEvent.In this code example, the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obter mais informações, consulte a documentação do Instrumentação de gerenciamento do Windows .For more information, see the Windows Management Instrumentation documentation. O cliente recebe eventos de forma síncrona chamando o método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Este exemplo pode ser testado com o início de um processo, como o bloco de notas, enquanto o código de exemplo está em execução.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

Comentários

Segurança do .NET Framework.NET Framework Security

Confiança total para o chamador imediato.Full trust for the immediate caller. Este membro não pode ser usado pelo código parcialmente confiável.This member cannot be used by partially trusted code. Para obter mais informações, consulte usando bibliotecas de código parcialmente confiável.For more information, see Using Libraries from Partially Trusted Code.

ManagementEventWatcher(String, String)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a WMI a consulta de evento de WMI determinada.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query. Para essa variante, a consulta e o escopo são especificados como cadeias de caracteres.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

O escopo de gerenciamento (namespace) em que o inspetor escuta eventos.The management scope (namespace) in which the watcher will listen for events.

query
String

A consulta que define os eventos para os quais o inspetor escutará.The query that defines the events for which the watcher will listen.

Exemplos

O exemplo a seguir mostra como o cliente recebe a notificação quando uma instância do Win32_Process é criada porque a classe de evento é __InstanceCreationEvent.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obter mais informações, consulte a documentação do Instrumentação de gerenciamento do Windows .For more information, see the Windows Management Instrumentation documentation. O cliente recebe eventos de forma síncrona chamando o método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Este exemplo pode ser testado com o início de um processo, como o bloco de notas, enquanto o código de exemplo está em execução.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

Comentários

Segurança do .NET Framework.NET Framework Security

Confiança total para o chamador imediato.Full trust for the immediate caller. Este membro não pode ser usado pelo código parcialmente confiável.This member cannot be used by partially trusted code. Para obter mais informações, consulte usando bibliotecas de código parcialmente confiável.For more information, see Using Libraries from Partially Trusted Code.

ManagementEventWatcher(ManagementScope, EventQuery, EventWatcherOptions)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a consulta de evento da WMI determinada, de acordo com as opções 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 essa variante, a consulta e o escopo são especificados como objetos.For this variant, the query and the scope are specified objects. O objeto de opções pode especificar opções, como informações de tempo limite e 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

Um ManagementScope que representa o escopo (namespace) em que o inspetor escutará eventos.A ManagementScope representing the scope (namespace) in which the watcher will listen for events.

query
EventQuery

Um EventQuery que representa uma consulta de evento WMI, que determina os eventos para os quais o inspetor vai escutar.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

options
EventWatcherOptions

Um EventWatcherOptions que representa as opções adicionais usadas para inspecionar eventos.An EventWatcherOptions representing additional options used to watch for events.

Exemplos

O exemplo a seguir mostra como o cliente recebe a notificação quando uma instância do Win32_Process é criada porque a classe de evento é __InstanceCreationEvent.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obter mais informações, consulte a documentação do Instrumentação de gerenciamento do Windows .For more information, see the Windows Management Instrumentation documentation. O cliente recebe eventos de forma síncrona chamando o método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Este exemplo pode ser testado com o início de um processo, como o bloco de notas, enquanto o código de exemplo está em execução.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

Comentários

Segurança do .NET Framework.NET Framework Security

Confiança total para o chamador imediato.Full trust for the immediate caller. Este membro não pode ser usado pelo código parcialmente confiável.This member cannot be used by partially trusted code. Para obter mais informações, consulte usando bibliotecas de código parcialmente confiável.For more information, see Using Libraries from Partially Trusted Code.

ManagementEventWatcher(String, String, EventWatcherOptions)

Inicializa uma nova instância da classe ManagementEventWatcher que escuta eventos em conformidade com a consulta de evento da WMI determinada, de acordo com as opções 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 essa variante, a consulta e o escopo são especificados como cadeias de caracteres.For this variant, the query and the scope are specified as strings. O objeto de opções pode especificar opções, como informações de tempo limite e 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

O escopo de gerenciamento (namespace) em que o inspetor escuta eventos.The management scope (namespace) in which the watcher will listen for events.

query
String

A consulta que define os eventos para os quais o inspetor escutará.The query that defines the events for which the watcher will listen.

options
EventWatcherOptions

Um EventWatcherOptions que representa as opções adicionais usadas para inspecionar eventos.An EventWatcherOptions representing additional options used to watch for events.

Exemplos

O exemplo a seguir mostra como o cliente recebe a notificação quando uma instância do Win32_Process é criada porque a classe de evento é __InstanceCreationEvent.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Para obter mais informações, consulte a documentação do Instrumentação de gerenciamento do Windows .For more information, see the Windows Management Instrumentation documentation. O cliente recebe eventos de forma síncrona chamando o método WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Este exemplo pode ser testado com o início de um processo, como o bloco de notas, enquanto o código de exemplo está em execução.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

Comentários

Segurança do .NET Framework.NET Framework Security

Confiança total para o chamador imediato.Full trust for the immediate caller. Este membro não pode ser usado pelo código parcialmente confiável.This member cannot be used by partially trusted code. Para obter mais informações, consulte usando bibliotecas de código parcialmente confiável.For more information, see Using Libraries from Partially Trusted Code.

Aplica-se a