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

Определение

Инициализация нового экземпляра класса ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class.

Перегрузки

ManagementEventWatcher()

Инициализация нового экземпляра класса ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class. Для дальнейшей инициализации следует задать свойства объекта.For further initialization, set the properties on the object. Это конструктор без параметров.This is the parameterless constructor.

ManagementEventWatcher(EventQuery)

Инициализирует новый экземпляр класса ManagementEventWatcher при наличии запроса WMI-события.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query.

ManagementEventWatcher(String)

Инициализирует новый экземпляр класса ManagementEventWatcher, если данный запрос WMI-событий представлен в виде строки.Initializes a new instance of the ManagementEventWatcher class when given a WMI event query in the form of a string.

ManagementEventWatcher(ManagementScope, EventQuery)

Инициализирует новый экземпляр ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query.

ManagementEventWatcher(String, String)

Инициализирует новый экземпляр ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query. Для этого варианта запрос и область задаются в виде строк.For this variant, the query and the scope are specified as strings.

ManagementEventWatcher(ManagementScope, EventQuery, EventWatcherOptions)

Выполняет инициализацию нового экземпляра класса ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий в соответствии с заданными параметрами.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Для этого варианта запрос и область представляют собой настраиваемые объекты.For this variant, the query and the scope are specified objects. Параметрический объект может задавать такие параметры, как время ожидания и контекст.The options object can specify options such as time-out and context information.

ManagementEventWatcher(String, String, EventWatcherOptions)

Инициализирует новый экземпляр класса ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий в соответствии с заданными параметрами.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Для этого варианта запрос и область задаются в виде строк.For this variant, the query and the scope are specified as strings. Параметрический объект может задавать такие параметры, как время ожидания и контекст.The options object can specify options such as a time-out and context information.

ManagementEventWatcher()

Инициализация нового экземпляра класса ManagementEventWatcher.Initializes a new instance of the ManagementEventWatcher class. Для дальнейшей инициализации следует задать свойства объекта.For further initialization, set the properties on the object. Это конструктор без параметров.This is the parameterless constructor.

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

Примеры

В следующем примере показано, как клиент получает уведомление при создании экземпляра 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

Комментарии

Безопасность .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.

ManagementEventWatcher(EventQuery)

Инициализирует новый экземпляр класса ManagementEventWatcher при наличии запроса 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)

Параметры

query
EventQuery

EventQuery представляет запрос WMI-событий, который определяет события, прослушиваемые наблюдателем.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

Примеры

В этом примере кода клиент получает уведомление при создании экземпляра Win32_Process , так как класс событий __InstanceCreationEvent.In this code example, 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
        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

Комментарии

Пространство имен, в котором будет ожидать события, — это пространство имен по умолчанию, установленное в данный момент.The namespace in which the watcher will be listening for events is the default namespace that is currently set.

Безопасность .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.

ManagementEventWatcher(String)

Инициализирует новый экземпляр класса ManagementEventWatcher, если данный запрос WMI-событий представлен в виде строки.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)

Параметры

query
String

Запрос WMI-событий, определяющий события, которые должен прослушивать наблюдатель.A WMI event query, which defines the events for which the watcher will listen.

Примеры

В следующем примере показано, как клиент получает уведомление при создании экземпляра 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
        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

Комментарии

Пространство имен, в котором будет ожидать события, — это пространство имен по умолчанию, установленное в данный момент.The namespace in which the watcher will be listening for events is the default namespace that is currently set.

Безопасность .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.

ManagementEventWatcher(ManagementScope, EventQuery)

Инициализирует новый экземпляр ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий.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)

Параметры

scope
ManagementScope

ManagementScope представляет область (пространство имен), в котором наблюдатель должен прослушивать события.A ManagementScope representing the scope (namespace) in which the watcher will listen for events.

query
EventQuery

EventQuery представляет запрос WMI-событий, который определяет события, прослушиваемые наблюдателем.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

Примеры

В этом примере кода клиент получает уведомление при создании экземпляра Win32_Process , так как класс событий __InstanceCreationEvent.In this code example, 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
        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

Комментарии

Безопасность .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.

ManagementEventWatcher(String, String)

Инициализирует новый экземпляр ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query. Для этого варианта запрос и область задаются в виде строк.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)

Параметры

scope
String

Область управления (пространство имен), в которой наблюдатель должен прослушивать события.The management scope (namespace) in which the watcher will listen for events.

query
String

Запрос, определяющий события, которые должен прослушивать наблюдатель.The query that defines the events for which the watcher will listen.

Примеры

В следующем примере показано, как клиент получает уведомление при создании экземпляра 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
        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

Комментарии

Безопасность .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.

ManagementEventWatcher(ManagementScope, EventQuery, EventWatcherOptions)

Выполняет инициализацию нового экземпляра класса ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий в соответствии с заданными параметрами.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Для этого варианта запрос и область представляют собой настраиваемые объекты.For this variant, the query and the scope are specified objects. Параметрический объект может задавать такие параметры, как время ожидания и контекст.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)

Параметры

scope
ManagementScope

ManagementScope представляет область (пространство имен), в котором наблюдатель должен прослушивать события.A ManagementScope representing the scope (namespace) in which the watcher will listen for events.

query
EventQuery

EventQuery представляет запрос WMI-событий, который определяет события, прослушиваемые наблюдателем.An EventQuery representing a WMI event query, which determines the events for which the watcher will listen.

options
EventWatcherOptions

EventWatcherOptions представляет дополнительные параметры отслеживания событий.An EventWatcherOptions representing additional options used to watch for 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
        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

Комментарии

Безопасность .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.

ManagementEventWatcher(String, String, EventWatcherOptions)

Инициализирует новый экземпляр класса ManagementEventWatcher, который прослушивает события, удовлетворяющие данному запросу WMI-событий в соответствии с заданными параметрами.Initializes a new instance of the ManagementEventWatcher class that listens for events conforming to the given WMI event query, according to the specified options. Для этого варианта запрос и область задаются в виде строк.For this variant, the query and the scope are specified as strings. Параметрический объект может задавать такие параметры, как время ожидания и контекст.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)

Параметры

scope
String

Область управления (пространство имен), в которой наблюдатель должен прослушивать события.The management scope (namespace) in which the watcher will listen for events.

query
String

Запрос, определяющий события, которые должен прослушивать наблюдатель.The query that defines the events for which the watcher will listen.

options
EventWatcherOptions

EventWatcherOptions представляет дополнительные параметры отслеживания событий.An EventWatcherOptions representing additional options used to watch for 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
        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

Комментарии

Безопасность .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.

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