ManagementEventWatcher.Query Свойство

Определение

Получает или задает критерии, которым должны отвечать события.Gets or sets the criteria to apply to events.

public:
 property System::Management::EventQuery ^ Query { System::Management::EventQuery ^ get(); void set(System::Management::EventQuery ^ value); };
public System.Management.EventQuery Query { get; set; }
member this.Query : System.Management.EventQuery with get, set
Public Property Query As EventQuery

Значение свойства

Запрос, применяемый к событиям.The query to apply to events.

Примеры

В следующем примере показано, как клиент получает уведомление при создании экземпляра Win32_Process , так как класс событий — __InstanceCreationEvent.The following example shows how the client receives notification when an instance of Win32_Process is created because the event class is __InstanceCreationEvent. Дополнительные сведения см. в документации по инструментарий управления Windows (WMI) .For more information, see the Windows Management Instrumentation documentation. Клиент получает события синхронно, вызывая метод WaitForNextEvent.The client receives events synchronously by calling the WaitForNextEvent method. Чтобы протестировать этот пример, можно во время выполнения кода запустить какой-нибудь процесс, такой как приложение Блокнот.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

Комментарии

Значение свойстваProperty Value

Критерии, применяемые к событиям, которые равны запросу событий.The criteria to apply to the events, which is equal to the event query.

Безопасность платформы .NET Framework.NET Framework Security

Полное доверие для непосредственно вызывающего метода.Full trust for the immediate caller. Этот член не может быть использован частично доверенным кодом.This member cannot be used by partially trusted code. Дополнительные сведения см. в разделе Использование библиотек из частично доверенного кода.For more information, see Using Libraries from Partially Trusted Code.

Применяется к