MSDN中有一段示例:
EventQuery 类
下面的示例演示当由于事件类是 __InstanceCreationEvent 而创建 Win32_Process 的实例时,客户端如何接收通知。有关更多信息,请参见位于 上的 MSDN Library 中的“Windows Management Instrumentation”文档。客户端通过调用 方法来同步接收事件。在运行此代码示例的同时,可以启动进程(如记事本)来测试此示例。
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;
}
}
编译成功,运行时出现异常:
Open an application (notepad.exe) to trigger an event.
Unhandled Exception: System.Runtime.InteropServices.COMException (0x800706BA): T
he RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 e
rrorCode, IntPtr errorInfo)
at System.Management.ManagementEventWatcher.WaitForNextEvent()
at EventWatcherPolling.Main(String[] args)
经GOOGLE到
受到提示打开
DCOM Server Process Launcher
服务,就正常了.
阅读(9003) | 评论(1) | 转发(0) |