EventQuery Класс

Определение

Представляет запрос события WMI.

public ref class EventQuery : System::Management::ManagementQuery
public class EventQuery : System.Management.ManagementQuery
type EventQuery = class
    inherit ManagementQuery
Public Class EventQuery
Inherits ManagementQuery
Наследование
EventQuery
Производный

Примеры

В следующем примере показано, как клиент получает уведомление при создании экземпляра Win32_Process , так как класс событий __InstanceCreationEvent. Дополнительные сведения см. в документации по инструментарию управления Windows . Клиент получает события синхронно, вызывая метод WaitForNextEvent. Чтобы протестировать этот пример, можно во время выполнения кода запустить какой-нибудь процесс, такой как приложение Блокнот.

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
        EventQuery query = new EventQuery();
        query.QueryString = "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 New EventQuery
        query.QueryString = "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, 50)

        ' 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

Конструкторы

EventQuery()

Инициализирует новый экземпляр класса EventQuery. Это конструктор без параметров.

EventQuery(String)

Выполняет инициализацию нового экземпляра класса EventQuery для заданного запроса.

EventQuery(String, String)

Выполняет инициализацию нового экземпляра класса EventQuery для заданного языка и запроса.

Свойства

QueryLanguage

Получает или задает язык запросов, который необходимо использовать в строке запроса, чтобы определить формат строки запроса.

(Унаследовано от ManagementQuery)
QueryString

Получает или задает запрос в текстовом формате.

(Унаследовано от ManagementQuery)

Методы

Clone()

Возвращает копию объекта.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ParseQuery(String)

Анализирует строку запроса и задает соответствующие значения свойств. Если запрос действителен, то будут проанализированы свойство имени класса и свойство условия, связанные с этим запросом.

(Унаследовано от ManagementQuery)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

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