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

  1. using System; 
  2. using System.Management; 
  3.  
  4. class Process 
  5.     public static void Main() 
  6.     { 
  7.         ManagementEventWatcher startWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); 
  8.         startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived); 
  9.         startWatch.Start(); 
  10.         ManagementEventWatcher stopWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace")); 
  11.         stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived); 
  12.         stopWatch.Start(); 
  13.         Console.WriteLine("Press ENTER to exit"); 
  14.         Console.ReadLine(); 
  15.         startWatch.Stop(); 
  16.         stopWatch.Stop(); 
  17.     } 
  18.  
  19.     static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) 
  20.     { 
  21.         Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value); 
  22.     } 
  23.  
  24.     static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) 
  25.     { 
  26.         string name = e.NewEvent.Properties["ProcessName"].Value.ToString(); 
  27.         int id = Convert.ToInt32(e.NewEvent.Properties["ProcessId"].Value); 
  28.         Console.WriteLine("Process started: {0}", name); 
  29.         if (name == "notepad.exe"
  30.         { 
  31.             System.Diagnostics.Process.GetProcessById(id).Kill(); 
  32.         } 
  33.     }