Tawee Taenkam
Tawee Taenkam

Reputation: 55

How to check if google chrome is running

I can close Google chrome via C# as follows:

Process[] chromeInstances = Process.GetProcessesByName("chrome");
foreach (Process p in chromeInstances)
{
    p.Kill();
}

but I do not know of a way to check if Google Chrome is running.

I would like to know way check that if google chrome is running or not first, thus will close Google chrome via C#.

Upvotes: 2

Views: 4948

Answers (2)

Cubicle.Jockey
Cubicle.Jockey

Reputation: 3328

If you would like to practice with dealing with the Chrome instances via the Process object you can do code snippets with LinqPad. Once you have this downloaded you can change your Language drop down to C# Program and paste this code in. Take your time and play here and try things before posting another question. I see that you kind of asked a question before, got a semi answer, took that semi answer then created a new question off of it that is still not 100% clear what you are looking for. StackOverflow is not here to do every step for you, make attempts first. If you are still stuck post YOUR code with a proper question to get help.

void Main()
{
    var chromeProcess = new ChromeProcess();
    Console.WriteLine(chromeProcess.AnyInstancesRunning());
    Console.WriteLine(chromeProcess.NumberOfInstancesRunning());
    chromeProcess.ChromeInstanceIds().Dump("Chrome Instance Ids");

    chromeProcess.KillChromeInstance(2816);

    //open and close a few chrome windows
    chromeProcess.RefreshInstances();
    Console.WriteLine(chromeProcess.AnyInstancesRunning());
    Console.WriteLine(chromeProcess.NumberOfInstancesRunning());
    chromeProcess.ChromeInstanceIds().Dump("Chrome Instance Ids");
}

// Define other methods and classes here
public class ChromeProcess
{
    private const string ImageName = "chrome";
    private IEnumerable<Process> _Instances;

    public ChromeProcess()
    {
        _Instances = Process.GetProcessesByName(ImageName);
    }

    public bool AnyInstancesRunning()
    {
        return _Instances.Any();
    }

    public int NumberOfInstancesRunning()
    {
        return _Instances.Count();
    }

    public IEnumerable<int> ChromeInstanceIds()
    {
        return _Instances.Select(i => i.Id).ToArray();
    }

    public void KillChromeInstance(int id)
    {
        var process = Process.GetProcessById(id);
        if(process.ProcessName != ImageName)
        {
            throw new Exception("Not a chrome instance.");
        }
        process.Kill();
    }

    public void RefreshInstances()
    {
        _Instances = Process.GetProcessesByName(ImageName);
    }
}

Upvotes: 0

Ateeq
Ateeq

Reputation: 823

simply check the array you got

    Process[] chromeInstances = Process.GetProcessesByName("chrome");
    if (chromeInstances.Length > 0)
    {
        //then chrome is up
    }
    else
    {
        //not working now
    }

Upvotes: 6

Related Questions