public static void Main()
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Dieses Programm registriert gestartete- und beendete Prozesse\n");
Console.WriteLine("Drücken Sie eine beliebige Taste um das Programm zu beenden\n");
Console.WriteLine(" Typ ║ Prozessname ║ PID ║ Exit ║ Parent ║ Session");
Console.WriteLine(" ║ ║ ║ Status ║ PID ║ ID ");
Console.WriteLine(" ══════╬════════════════════════════════╬═══════╬════════════╬════════╬════════");
ManagementEventWatcher startWatch = null;
ManagementEventWatcher stopWatch = null;
try
{
//Eventwatcher initilisieren
startWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
startWatch.EventArrived += new EventArrivedEventHandler(processStart);
startWatch.Start();
stopWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
stopWatch.EventArrived += new EventArrivedEventHandler(processStop);
stopWatch.Start();
while (!Console.KeyAvailable) Thread.Sleep(50);//Auf Benutzereingabe warten, um das Programm zu beenden.
}
catch (Exception ex)
{
Console.WriteLine("Leider ist ein Fehler aufgetreten.");
Console.WriteLine("Fehlermeldung: {0}", ex.Message);
}
finally
{
//Eventwatcher wieder beenden
if (startWatch != null)
startWatch.Stop();
if (stopWatch != null)
stopWatch.Stop();
}
}
static void processStop(object sender, EventArrivedEventArgs e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" Stopp ║ {0,-31}║ {1,5} ║ {2,10} ║ {3,6} ║ {4,7}",
e.NewEvent.Properties["ProcessName"].Value,
e.NewEvent.Properties["ProcessID"].Value,
e.NewEvent.Properties["ExitStatus"].Value,
e.NewEvent.Properties["ParentProcessID"].Value,
e.NewEvent.Properties["SessionID"].Value);
}
static void processStart(object sender, EventArrivedEventArgs e)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" Start ║ {0,-31}║ {1,5} ║ {2,10} ║ {3,6} ║ {4,7}",
e.NewEvent.Properties["ProcessName"].Value,
e.NewEvent.Properties["ProcessID"].Value,
"-",
e.NewEvent.Properties["ParentProcessID"].Value,
e.NewEvent.Properties["SessionID"].Value);
}