mehran
mehran

Reputation: 19

Check whether an application is running?

I want to check if a program is running or not. For example, check that the program (notepad) is running.

I tried this code :

Process[] pname = Process.GetProcessesByName("App name");
if (pname.Length != 0) { 
   //run 
}

I want to check. But when the burst is checking, the program (app name) stops. And whenever the checking operation is completed, the program (app name) starts

public void BS() 
    bool key = true;
    while (key) {
        Process[] pname = Process.GetProcessesByName("appname");
        if (pname.Length != 0) {
            textBox1.Text += "run";
        } else {
            key = false;
            textBox1.Text += "stop";
        }
    }
}

The appname.exe program should continue to work in any case, but when I put this in my form to check appname.exe the appname.exe program stops.

Whenever the while cycle is stopped, appname.exe starts up.

Upvotes: 1

Views: 396

Answers (2)

Jaydeep Jadav
Jaydeep Jadav

Reputation: 836

Your program is going into the infinite loop which might causing the application stop and start.

Try putting some thread sleep between checking again.

public void BS()
{
    bool key = true;
    while (key)
    {
        Process[] pname = Process.GetProcessesByName("appname");
        if (pname.Length != 0)
        {
            textBox1.Text += "run";
        }
        else
        {
            key = false;
            textBox1.Text += "stop";
        }
        System.Threading.Thread.Sleep(1000); //For 1 Second
    }
}

Upvotes: 0

Taha
Taha

Reputation: 675

This is a way to do it with the name:

Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
  MessageBox.Show("nothing");
else
  MessageBox.Show("run");

You can loop all process to get the ID for later manipulation:

Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
   Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}

Upvotes: 1

Related Questions