2012-07-28 17 views
5

有一些事件通过WMI暴露,但我似乎无法找到订阅和被警告这些事件的任何实例。特别是我想实施WmiMonitorBrightnessEvent将通知推送给Growl/Snarl。如何消耗在C#WMI活动

+0

你有什么代码到目前为止的文件?你有没有回顾过等待创建WMI实例的例子[这里](http://msdn.microsoft.com/en-us/library/system.management.managementeventwatcher.aspx)? – Richard 2012-07-28 16:30:30

+1

使用WMI Code Creator实用程序,单击“接收事件”选项卡。它会自动为您生成C#代码。这个在我的机器上不起作用,并不罕见。 – 2012-07-28 17:39:31

+0

@HansPassant:谢谢,从来没有听说过WMI代码创建器实用程序,将检查出来。我没有代码,因为我甚至不知道从哪里开始。下面的RRUZ答案肯定能帮助我开始。 – esac 2012-07-28 20:17:44

回答

9

这是为接收WmiMonitorBrightnessEvent WMI事件的样本代码。

using System; 
using System.Collections.Generic; 
using System.Management; 
using System.Text; 


namespace GetWMI_Info 
{ 
    public class EventWatcherAsync 
    { 
     private void WmiEventHandler(object sender, EventArrivedEventArgs e) 
     { 
      Console.WriteLine("Active :   " + e.NewEvent.Properties["Active"].Value.ToString()); 
      Console.WriteLine("Brightness :  " + e.NewEvent.Properties["Brightness"].Value.ToString()); 
      Console.WriteLine("InstanceName : " + e.NewEvent.Properties["InstanceName"].Value.ToString()); 

     } 

     public EventWatcherAsync() 
     { 
      try 
      { 
       string ComputerName = "localhost"; 
       string WmiQuery; 
       ManagementEventWatcher Watcher; 
       ManagementScope Scope; 


       if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) 
       { 
        ConnectionOptions Conn = new ConnectionOptions(); 
        Conn.Username = ""; 
        Conn.Password = ""; 
        Conn.Authority = "ntlmdomain:DOMAIN"; 
        Scope = new ManagementScope(String.Format("\\\\{0}\\root\\WMI", ComputerName), Conn); 
       } 
       else 
        Scope = new ManagementScope(String.Format("\\\\{0}\\root\\WMI", ComputerName), null); 
       Scope.Connect(); 

       WmiQuery ="Select * From WmiMonitorBrightnessEvent"; 

       Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery)); 
       Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler); 
       Watcher.Start(); 
       Console.Read(); 
       Watcher.Stop(); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace); 
      } 

     } 

     public static void Main(string[] args) 
     { 
      Console.WriteLine("Listening {0}", "WmiMonitorBrightnessEvent"); 
      Console.WriteLine("Press Enter to exit"); 
      EventWatcherAsync eventWatcher = new EventWatcherAsync(); 
      Console.Read(); 
     } 
    } 
} 

如果你是新来的WMI尝试使用像WMI Delphi Code Creator的工具和阅读有关这个​​话题Receiving a WMI Event