zoukankan      html  css  js  c++  java
  • C#捕捉进程开始和结束事件

    通过C#捕捉进程开始和结束事件,禁止notepad.exe运行。这比用钩子的代码少多了。但我测试时,偶尔有事件被漏掉的情况。要求不太苛刻的地方,还是可以用用的。

    using System; 
    using System.Management; 
     
    class Process 
    { 
        public static void Main() 
        { 
            ManagementEventWatcher startWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); 
            startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived); 
            startWatch.Start(); 
            ManagementEventWatcher stopWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace")); 
            stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived); 
            stopWatch.Start(); 
            Console.WriteLine("Press ENTER to exit"); 
            Console.ReadLine(); 
            startWatch.Stop(); 
            stopWatch.Stop(); 
        } 
     
        static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) 
        { 
            Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value); 
        } 
     
        static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) 
        { 
            string name = e.NewEvent.Properties["ProcessName"].Value.ToString(); 
            int id = Convert.ToInt32(e.NewEvent.Properties["ProcessId"].Value); 
            Console.WriteLine("Process started: {0}", name); 
            if (name == "notepad.exe") 
            { 
                System.Diagnostics.Process.GetProcessById(id).Kill(); 
            } 
        } 
    } 
    

      

  • 相关阅读:
    instance
    iptables
    centos系统准备
    Leecode no.236 二叉树的最近公共祖先
    Leecode no.235 二叉搜索树的最近公共祖先
    leecode no.98 验证二叉搜索树
    leecode no.109 有序链表转换二叉搜索树
    leecode no.113 路径总和 II
    Leecode no.112 路径总和
    Leecode no.111 二叉树的最小深度
  • 原文地址:https://www.cnblogs.com/chengulv/p/2850687.html
Copyright © 2011-2022 走看看