Search code examples
c#processdetection

Fast Process Detection


i have this piece of code to detect a Process:

private Boolean IsGameRunning()
    {
        Process[] game = Process.GetProcesses();
        foreach (Process process in game)
        {
            if (process.ProcessName.Contains("GameWindow"))
            {
                return true;
            }
        }
        return false;
    }

Since the code has to run a lot of times because it is inside a Timer, is there any way to improve the speed of the process? I do not have any control over the game.

This code is inside a timer always enabled with an interval of 2000-3000 ms:

if (IsGameRunning())
            {
                Do stuff
            }
            else
            {

                Status("Waiting for game to start");
            }

Solution

  • Given that the process is launched by another, in this case Steam, we can narrow the list to search to only child processes.

    First, need to get the parent process id (PID).

    var parentProcess = Process.GetProcesses().FirstOrDefault(x => x.ProcessName == "Steam");
    

    Then using the Windows Management Instrumentation (accessed using the System.Management.dll), you can then search only the child processes.

    bool IsGameRunning(int parentProcess, string childExecutableName)
    {
        var query = string.Format("SELECT * FROM Win32_Process WHERE ParentProcessId = {0} AND Name = '{1}'", parentProcess, childExecutableName);
    
        using (var searcher = new ManagementObjectSearcher(query))
        using (var results = searcher.Get())
        {
            return (results.Count > 0);
        }
    }
    

    e.g. IsGameRunning(parentProcess.Id, "SuperMeatBoy.exe")

    No guarantee that this is faster as I haven't done any comparative testing, however from prior experience using the WMI is more performant than iterating a list of processes.

    If you want to go further, a more advanced solution would be to hook up events to tell you process is created and deleted using a ManagementEventWatcher as shown in this blog post http://weblogs.asp.net/whaggard/438006.