目錄
返回目錄
進程啟動或結束監控
代碼:
//注意:引用System.Management.dll 和 using System.Management;
static void Main(string[] args)
{
//建立WQL事件查詢,用於執行個體建立
var qCreate = new WqlEventQuery("__InstanceCreationEvent",
TimeSpan.FromSeconds(1), //WHTHIN = 1
"TargetInstance ISA 'Win32_Process'");
//建立WQL事件查詢,用於執行個體刪除
var qDelete = new WqlEventQuery("__InstanceDeletionEvent",
TimeSpan.FromSeconds(1), //WHTHIN = 1
"TargetInstance ISA 'Win32_Process'");
//建立事件查詢的接聽程式(ManagementEventWatcher)
var wCreate = new ManagementEventWatcher(qCreate);
var wDelete = new ManagementEventWatcher(qDelete);
//事件註冊代碼
wCreate.EventArrived += (sender, e) =>
{
Console.WriteLine("運行:{0}", GetInfo(e.NewEvent));
};
wDelete.EventArrived += (sender, e) =>
{
Console.WriteLine("關閉:{0}", GetInfo(e.NewEvent));
};
//非同步開始偵聽
wCreate.Start();
wDelete.Start();
Console.WriteLine("按任意鍵停止監控");
Console.ReadKey(true);
}
//輸出事件對應的ManagementBaseObject(本例中的Win32_Process執行個體)的資訊
static string GetInfo(ManagementBaseObject mobj)
{
var instance = (ManagementBaseObject)mobj["TargetInstance"];
return string.Format("{0} - {1}", instance["Name"], DateTime.Now);
}
返回目錄
可移動磁碟插入或刪除監控
代碼:
//注意:引用System.Management.dll 和 using System.Management;
static void Main(string[] args)
{
//建立WQL事件查詢,用於執行個體建立
//加入條件判斷 TargetInstance.DriveType = 2
//代表判斷Win32_LogicalDisk.DriveType屬性,2則代表可移動磁碟
var qCreate = new WqlEventQuery("__InstanceCreationEvent",
TimeSpan.FromSeconds(1),
"TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2");
//建立WQL事件查詢,用於執行個體刪除
var qDelete = new WqlEventQuery("__InstanceDeletionEvent",
TimeSpan.FromSeconds(1),
"TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2");
//建立事件查詢的接聽程式(ManagementEventWatcher)
var wCreate = new ManagementEventWatcher(qCreate);
var wDelete = new ManagementEventWatcher(qDelete);
//事件註冊代碼
wCreate.EventArrived += (sender, e) =>
{
Console.WriteLine("接入可移動磁碟:{0}", GetInfo(e.NewEvent));
};
wDelete.EventArrived += (sender, e) =>
{
Console.WriteLine("拔出可移動磁碟:{0}", GetInfo(e.NewEvent));
};
//非同步開始偵聽
wCreate.Start();
wDelete.Start();
Console.WriteLine("按任意鍵停止監控");
Console.ReadKey(true);
}
//輸出事件對應的ManagementBaseObject(本例中的Win32_LogicalDisk執行個體)的資訊
static string GetInfo(ManagementBaseObject mobj)
{
var instance = (ManagementBaseObject)mobj["TargetInstance"];
return string.Format("{0} - {1}", instance["Name"], DateTime.Now);
}