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
- Наследование
- Производный
В следующем примере показано, как клиент получает уведомление при создании экземпляра 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
Event |
Инициализирует новый экземпляр класса EventQuery. Это конструктор без параметров. |
Event |
Выполняет инициализацию нового экземпляра класса EventQuery для заданного запроса. |
Event |
Выполняет инициализацию нового экземпляра класса EventQuery для заданного языка и запроса. |
Query |
Получает или задает язык запросов, который необходимо использовать в строке запроса, чтобы определить формат строки запроса. (Унаследовано от ManagementQuery) |
Query |
Получает или задает запрос в текстовом формате. (Унаследовано от ManagementQuery) |
Clone() |
Возвращает копию объекта. |
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
Get |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
Get |
Возвращает объект Type для текущего экземпляра. (Унаследовано от Object) |
Memberwise |
Создает неполную копию текущего объекта Object. (Унаследовано от Object) |
Parse |
Анализирует строку запроса и задает соответствующие значения свойств. Если запрос действителен, то будут проанализированы свойство имени класса и свойство условия, связанные с этим запросом. (Унаследовано от ManagementQuery) |
To |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Продукт | Версии |
---|---|
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |