c#Process监控进程 与ManagementEventWatcher 监控进程

it2022-05-05  162

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

1.使用Process监控->播放器的打开与关闭,这里的案例主要监控了Windows播放器和暴风影音播放器,过程中使用了Timer定时监控,但在实际的项目中不建议这样使用,会浪费电脑的性能,最好是能够以自动回调的方式去实现,以下是一个参考。

2.引用:

using System.Collections.Generic; using System.Diagnostics;

3.代码:

private Dictionary<string, bool> _allPlayerList; /// <summary> /// 播放器集合[(wmplayer)windows播放器,(stormplayer)暴风影音] /// </summary> public Dictionary<string, bool> AllPlayerList { get { if (_allPlayerList == null) { _allPlayerList = new Dictionary<string, bool>() { { "wmplayer", false }, { "stormplayer", false } }; } return _allPlayerList; } set { _allPlayerList = value; } } /// <summary> /// 监控进程 /// </summary> public void Monitor_Process() { System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Interval = 3000; aTimer.Elapsed += new System.Timers.ElapsedEventHandler(Process_Open); aTimer.AutoReset = true; aTimer.Enabled = true; aTimer.Start(); } /// <summary> /// 进程打开 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Process_Open(object sender, EventArgs e) { foreach (var item in AllPlayerList.ToList()) { if (!item.Value) { Process[] processesArray = Process.GetProcessesByName(item.Key.ToString()); foreach (Process process in processesArray) { if (process.ProcessName.ToLower() == item.Key.ToString()) { process.EnableRaisingEvents = true; process.Exited += new EventHandler(Process_Exited); AllPlayerList.Remove(item.Key); AllPlayerList.Add(item.Key,true); MessageBox.Show("打开" + item.Key + ".exe"); } } } } } /// <summary> /// 进程关闭 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Process_Exited(object sender, EventArgs e) { Process p = (Process)sender; AllPlayerList.Remove(p.ProcessName.ToLower()); AllPlayerList.Add(p.ProcessName.ToLower(), false); MessageBox.Show("关闭" + p.ProcessName + ".exe"); }

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

针对上面的案例,我又重新封装了一下,让代码独立,方便阅读方便调用,打开与关闭都使用事件回调的方式。

public class MonitorProcess { /// <summary> /// 委托 /// </summary> /// <param name="processName"></param> /// <param name="e"></param> public delegate void PlayerEventHandler(string processName); /// <summary> /// 事件 /// </summary> public static event PlayerEventHandler _playerEvent; /// <summary> /// 委托事件(打开播放器) /// </summary> private static PlayerEventHandler _openEvent; /// <summary> /// 委托事件(关闭播放器) /// </summary> private static EventHandler _exitedEvent; //定时监控 private static System.Timers.Timer _timer; /// <summary> /// 定时监控 /// </summary> public static System.Timers.Timer Time { get { if (_timer == null) { _timer = new System.Timers.Timer(); //定时查看播放器是否被打开 _timer.Elapsed += new System.Timers.ElapsedEventHandler(Process_Open); _timer.AutoReset = true; _timer.Enabled = true; //注册打开委托事件 _playerEvent += _openEvent; } return _timer; } set { _timer = value; } } /// <summary> /// 开始监控播放器 /// </summary> /// <param name="timerInterval">定时监控时间</param> /// <param name="openEvent">打开回调事件</param> /// <param name="exitedEvent">退出回调事件</param> /// <param name="allPlayerList">播放器集合</param> public static void StartMonitorProcess(int timerInterval, PlayerEventHandler openEvent, EventHandler exitedEvent,List<string> allPlayerList) { _openEvent = openEvent; _exitedEvent = exitedEvent; AllPlayerList = allPlayerList; Time.Interval = timerInterval; //*** Process_Open(null, null); Time.Start(); } /// <summary> /// 停止监控播放器 /// </summary> public static void StopMonitorProcess() { Time.Stop(); AllPlayerList.Clear(); CurrentOpenPlayerList.Clear(); } //播放器集合 private static List<string> _allPlayerList; /// <summary> /// 播放器集合 /// </summary> public static List<string> AllPlayerList { get { if (_allPlayerList == null) { _allPlayerList = new List<string>(); } return _allPlayerList; } set { _allPlayerList = value; } } //当前打开播放器 private static List<string> _currentOpenPlayerList; /// <summary> /// 当前打开播放器 /// </summary> private static List<string> CurrentOpenPlayerList { get { if (_currentOpenPlayerList == null) { _currentOpenPlayerList = new List<string>(); } return _currentOpenPlayerList; } set { _currentOpenPlayerList = value; } } /// <summary> /// 监控播放器逻辑 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void Process_Open(object sender, EventArgs e) { try { foreach (var item in AllPlayerList.ToList()) { Process[] processesArray = Process.GetProcessesByName(item.ToString()); if (processesArray.Count() > 0) { foreach (Process process in processesArray) { if (process.ProcessName.ToLower() == item.ToString() && CurrentOpenPlayerList.Where(x => x == item.ToString()).FirstOrDefault() == null) { CurrentOpenPlayerList.Add(item.ToString()); process.EnableRaisingEvents = true; process.Exited += _exitedEvent; _playerEvent.Invoke(item.ToString()); } } } else { CurrentOpenPlayerList.Remove(item.ToString()); } } } catch (Exception ex) { Console.WriteLine("Exception {0} Trace {1}", ex.Message, ex.StackTrace); } } }

调用方式:

//开始监控 MonitorProcess.StartMonitorProcess(6000, new PlayerEventHandler(OpenPlayerEvent), new EventHandler(ExitedPlayerEvent), allPlayerList); /// <summary> /// 打开播放器时回调事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void OpenPlayerEvent(string processName) { _messageEvent("用户打开了:" + processName + ".exe"); CurrentOpenPlayerList.Add(processName); OperationSuperResolution(); } /// <summary> /// 退出播放器时回调事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void ExitedPlayerEvent(object sender, EventArgs e) { Process p = (Process)sender; string processName = p.ProcessName.ToLower(); _messageEvent("用户关闭了:" + processName + ".exe"); CurrentOpenPlayerList.Remove(processName); OperationSuperResolution(); } //停止监控 MonitorProcess.StopMonitorProcess();

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

这里记录一下ManagementEventWatcher,使用ManagementEventWatcher 监控,系统的所有进程开启和停止,这里都会收到通知,管理员权限运行。【控制台应用】

代码:

using System; using System.Management; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static ManagementEventWatcher startWatch = null; static ManagementEventWatcher stopWatch = null; static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"\n\t请输入(y/n)[y:开始监控 n:停止监控]"); while (true) { string input = Console.ReadLine().ToLower(); if (input == "n" && startWatch != null && stopWatch != null) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"------------------------------------------------------------"); StopMonitor(); } else if (input == "y" && startWatch == null && stopWatch == null) { StartMonitor(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"------------------------------------------------------------"); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"\n\t输入错误!"); } } } private static void StartMonitor() { Task.Run(() => { if (startWatch == null) { startWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); startWatch.EventArrived += StartWatch_EventArrived; } startWatch.Start(); if (stopWatch == null) { stopWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace")); stopWatch.EventArrived += StopWatch_EventArrived; } stopWatch.Start(); }); } private static void StopWatch_EventArrived(object sender, EventArrivedEventArgs e) { string pid = e.NewEvent.Properties["ProcessID"].Value.ToString(); string name = e.NewEvent.Properties["ProcessName"].Value.ToString(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"\n\tStop >【" + pid + "|" + name + "】" + DateTime.Now); } private static void StartWatch_EventArrived(object sender, EventArrivedEventArgs e) { string pid = e.NewEvent.Properties["ProcessID"].Value.ToString(); string name = e.NewEvent.Properties["ProcessName"].Value.ToString(); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"\n\tStart >【" + pid + "|" + name + "】" + DateTime.Now); } private static void StopMonitor() { startWatch.EventArrived -= StartWatch_EventArrived; stopWatch.EventArrived -= StopWatch_EventArrived; startWatch = null; stopWatch = null; } } }

 


最新回复(0)