Đây là mã mẫu để nhận sự kiện W2 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();
}
}
}
Nếu bạn là người mới đến WMI hãy thử sử dụng một công cụ như WMI Delphi Code Creator
và đọc các tài liệu liên quan đến chủ đề này Receiving a WMI Event
đang làm những gì bạn có cho đến nay? Bạn đã xem xét ví dụ về việc chờ đợi một sự sáng tạo ví dụ WMI [ở đây] (http://msdn.microsoft.com/en-us/library/system.management.managementeventwatcher.aspx) chưa? – Richard
Sử dụng tiện ích WMI Code Creator, nhấp vào tab "Nhận sự kiện". Nó tự động tạo mã C# cho bạn. Cái này không hoạt động trên máy tính của tôi, không phải bất thường. –
@ HansPassant: cảm ơn, không bao giờ nghe nói về tiện ích tạo mã WMI, sẽ kiểm tra điều đó. Tôi không có mã vì tôi thậm chí không biết bắt đầu từ đâu. Câu trả lời RRUZ dưới đây chắc chắn sẽ giúp tôi bắt đầu. – esac