<转>.NET(C#)使用WMI事件查询实现对进程和可移动磁盘的监控

进程启动或结束监控

 

image

 

代码:

 1   //注意:引用System.Management.dll 和 using System.Management;
2
3 staticvoid Main(string[] args)
4
5 {
6
7 //创建WQL事件查询,用于实例创建
8
9 var qCreate =newWqlEventQuery("__InstanceCreationEvent",
10
11 TimeSpan.FromSeconds(1), //WHTHIN = 1
12
13 "TargetInstance ISA 'Win32_Process'");
14
15 //创建WQL事件查询,用于实例删除
16
17 var qDelete =newWqlEventQuery("__InstanceDeletionEvent",
18
19 TimeSpan.FromSeconds(1), //WHTHIN = 1
20
21 "TargetInstance ISA 'Win32_Process'");
22
23
24
25 //创建事件查询的侦听器(ManagementEventWatcher)
26
27 var wCreate =newManagementEventWatcher(qCreate);
28
29 var wDelete =newManagementEventWatcher(qDelete);
30
31
32
33 //事件注册代码
34
35 wCreate.EventArrived += (sender, e) =>
36
37 {
38
39 Console.WriteLine("运行:{0}", GetInfo(e.NewEvent));
40
41 };
42
43 wDelete.EventArrived += (sender, e) =>
44
45 {
46
47 Console.WriteLine("关闭:{0}", GetInfo(e.NewEvent));
48
49 };
50
51
52
53 //异步开始侦听
54
55 wCreate.Start();
56
57 wDelete.Start();
58
59
60
61 Console.WriteLine("按任意键停止监控");
62
63 Console.ReadKey(true);
64
65 }
66
67
68
69 //输出事件对应的ManagementBaseObject(本例中的Win32_Process实例)的信息
70
71 staticstring GetInfo(ManagementBaseObject mobj)
72
73 {
74
75 var instance = (ManagementBaseObject)mobj["TargetInstance"];
76
77 returnstring.Format("{0} - {1}", instance["Name"], DateTime.Now);
78
79 }
80
81

 

 

 

可移动磁盘插入或删除监控

 

image

代码:

 1  //注意:引用System.Management.dll 和 using System.Management;
2
3 staticvoid Main(string[] args)
4
5 {
6
7 //创建WQL事件查询,用于实例创建
8
9 //加入条件判断 TargetInstance.DriveType = 2
10
11 //代表判断Win32_LogicalDisk.DriveType属性,2则代表可移动磁盘
12
13 var qCreate =newWqlEventQuery("__InstanceCreationEvent",
14
15 TimeSpan.FromSeconds(1),
16
17 "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2");
18
19 //创建WQL事件查询,用于实例删除
20
21 var qDelete =newWqlEventQuery("__InstanceDeletionEvent",
22
23 TimeSpan.FromSeconds(1),
24
25 "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2");
26
27
28
29 //创建事件查询的侦听器(ManagementEventWatcher)
30
31 var wCreate =newManagementEventWatcher(qCreate);
32
33 var wDelete =newManagementEventWatcher(qDelete);
34
35
36
37 //事件注册代码
38
39 wCreate.EventArrived += (sender, e) =>
40
41 {
42
43 Console.WriteLine("接入可移动磁盘:{0}", GetInfo(e.NewEvent));
44
45 };
46
47 wDelete.EventArrived += (sender, e) =>
48
49 {
50
51 Console.WriteLine("拔出可移动磁盘:{0}", GetInfo(e.NewEvent));
52
53 };
54
55
56
57 //异步开始侦听
58
59 wCreate.Start();
60
61 wDelete.Start();
62
63
64
65 Console.WriteLine("按任意键停止监控");
66
67 Console.ReadKey(true);
68
69 }
70
71
72
73 //输出事件对应的ManagementBaseObject(本例中的Win32_LogicalDisk实例)的信息
74
75 staticstring GetInfo(ManagementBaseObject mobj)
76
77 {
78
79 var instance = (ManagementBaseObject)mobj["TargetInstance"];
80
81 returnstring.Format("{0} - {1}", instance["Name"], DateTime.Now);
82
83 }

 

你可能感兴趣的:(.net)