11,581 questions
Hi @MIPAKTEH_1 , Welcome to Microsoft Q&A,
ProcessStartEventArrived is the callback function when a WMI event arrives, but in your code, it does not seem to be correctly associated with the method in the Form1 class.
using System;
using System.Management;
using System.Windows.Forms;
namespace xxx
{
public partial class Form1 : Form
{
private ManagementEventWatcher processStartWatcher;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
StartProcessMonitor();
}
private void StartProcessMonitor()
{
try
{
var query = new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace");
processStartWatcher = new ManagementEventWatcher(query);
processStartWatcher.EventArrived += ProcessStartEventArrived;
processStartWatcher.Start();
Console.WriteLine("Monitoring process start events...");
}
catch (Exception ex)
{
Console.WriteLine($"Monitor start failed: {ex.Message}");
}
}
private void ProcessStartEventArrived(object sender, EventArrivedEventArgs e)
{
string processName = e.NewEvent.Properties["ProcessName"]?.Value?.ToString() ?? "Unknown process";
string processID = e.NewEvent.Properties["ProcessID"]?.Value?.ToString() ?? "Unknown PID";
// Output to console
Console.WriteLine($"A new process was detected: process name = {processName}, process ID = {processID}");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
StopProcessMonitor();
}
private void StopProcessMonitor()
{
if (processStartWatcher != null)
{
processStartWatcher.Stop();
processStartWatcher.Dispose();
processStartWatcher = null;
}
Console.WriteLine("The monitor has stopped.");
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.