Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when specific program program has closed with C#

Tags:

java

c#

process

I have two different .jar programs running on the same machine. I want to be able to detect when one of them has been closed, or is no longer running.

This issue that I am having is, when running this code:

  var allProc = Process.GetProcesses();
  foreach (var p in allProc)

  comboBox1.Items.Add(p.ProcessName);
  comboBox1.Sorted = true;

It only shows a single instance of Java running, and not only that it doesn't show either of the process names.

The program I want to monitor uses a lot of RAM, so I thought about monitoring RAM usage and doing what I need when it drops below a certain level, but to me that sounds like a hacky way of doing it and other factors could effect it.

Any ideas?

like image 698
James Morrish Avatar asked Mar 03 '26 16:03

James Morrish


1 Answers

You can use System.Diagnostics.Process to get the Process Id for the parent process you're looking for.

From there you can then use WMI through the (System.Management) namespace to search for the child processes:

Process[] javaProcesses = Process.GetProcessesByName("somejavaapp.exe");
foreach (Process proc in javaProcesses)
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(
    "SELECT * " +
    "FROM Win32_Process " +
    "WHERE ParentProcessId=" + proc.Id);

    ManagementObjectCollection collection = searcher.Get();

    // Choose what to do with the child processes.
    foreach (var childProcess in collection)
    {
        var childProcessId = (UInt32)childProcess["ProcessId"];
    }
}
like image 163
Chris Cruz Avatar answered Mar 05 '26 06:03

Chris Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!