简体   繁体   中英

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.

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);
}

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM