c# Process監控進程 與 ManagementEventWatcher 監控進程

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

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;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章