Officialwardog

RE: Help Start and stop Proccess when task manager opens

Jul 2nd, 2018
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. using System;
  2. using System.Management;
  3.  
  4. namespace HackForums.Example
  5. {
  6.     class Program
  7.     {
  8.         static void Main()
  9.         {
  10.             ProcessInfo taskmgr = new ProcessInfo("Taskmgr.exe");
  11.             taskmgr.Started += TaskmgrStarted;
  12.             taskmgr.Terminated += TaskmgrTerminated;
  13.             while (true){}
  14.         }
  15.  
  16.         private static void TaskmgrStarted(object sender, EventArgs e)
  17.         {
  18.             Console.WriteLine("Task Manager is now open");
  19.         }
  20.  
  21.         private static void TaskmgrTerminated(object sender, EventArgs e)
  22.         {
  23.             Console.WriteLine("Task Manager is now closed");
  24.         }
  25.     }
  26.  
  27.     public class ProcessInfo
  28.     {
  29.         public delegate void StartedEventHandler(object sender, EventArgs e);
  30.         public delegate void TerminatedEventHandler(object sender, EventArgs e);
  31.        
  32.         public StartedEventHandler Started;
  33.         public TerminatedEventHandler Terminated;
  34.  
  35.         public ProcessInfo(string appName)
  36.         {
  37.             string pol = "2";
  38.             string scope = @"\\.\root\CIMV2";
  39.             string queryString =  
  40.                 $"SELECT * FROM __InstanceOperationEvent WITHIN {pol} WHERE TargetInstance ISA \'Win32_Process\' AND TargetInstance.Name = '{appName}'";
  41.                                
  42.             ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
  43.             watcher.EventArrived += OnEventArrived;        
  44.             watcher.Start();
  45.         }
  46.  
  47.         private void OnEventArrived(object sender, EventArrivedEventArgs e)
  48.         {
  49.             try
  50.             {
  51.                 string eventName = e.NewEvent.ClassPath.ClassName;
  52.  
  53.                 if (string.Compare(eventName, "__InstanceCreationEvent", StringComparison.Ordinal) == 0)
  54.                 {
  55.                     Started?.Invoke(this, e);
  56.                 }
  57.                 else if (string.Compare(eventName, "__InstanceDeletionEvent", StringComparison.Ordinal) == 0)
  58.                 {
  59.                     Terminated?.Invoke(this, e);
  60.                 }              
  61.             }
  62.             catch (Exception ex)
  63.             {
  64.                 System.Diagnostics.Debug.WriteLine(ex.Message);
  65.             }
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment