Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I just created a simple program that checks a process is currently running or not.Which means when i run a program named console1.In this program it shows that the "Console1 is currently running".But,when i closed console1 it showing "console1 is running" instead of "console1 is not running".I applied looping,goto and console.clear() etc...But nothing worked.Following is the code i used.Could you tell how to fix it?
C#
static void Main(string[] args)
{

Process[] myProcesss;
myProcesss = Process.GetProcessesByName("console1.vshost");
if (myProcesss.Length > 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Running");
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("not running");
}
Console.ReadLine();


}

Thank you
Posted

It depends on what you are doing in your loop - you have to get the list of running processes each time round, or it will never change. This is how I do it:
C#
static void Main(string[] args)
    {
    while (true)
        {
        Console.WriteLine(IsRunning("Console2"));
        Thread.Sleep(500);
        }
    }
private static bool IsRunning(string name)
    {
    Process[] processes = Process.GetProcesses();

    foreach (Process p in processes)
        {
        if (p.ProcessName == name)
            {
            return true;
            }
        }
    return false;
    }
 
Share this answer
 
Comments
sreenathpktr 20-Oct-11 4:09am    
That's it..Thank you very much.
Your question is not clear. However, you check not only on number of fetched process but also for the process itself.

Probably your instance is also fetched, check that

Process currentProcess = Process.GetCurrentProcess();


your current process is not inside the retrieved array.

Each process has it's own unique Id. Print them out and print out for all retrieved processes their id and check and post the result.


Cheers
 
Share this answer
 
Your program tells you that console1.vshost.exe is running when you think it is not. Who is wrong you or the program?

The Processes tab of the Task Manager will tell you if there really is a problem to fix. I think you are going to be suprised!

Alan.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900