How to know if a process is running in windows using c# or . bat?

Asked

Viewed 1,160 times

0

I am wanting to create an application that runs in the background and that monitors some service to know if it is in execution or not someone could give me a light?

  • 2

    Why do you have C++ in the tags?

  • and almost the same thing both

  • In fact, they are very different, despite the similar name.

2 answers

2


Using C#, you can use the class Process. See in the example below where I check if the notepad is open

Process[] processos = Process.GetProcessesByName("notepad");

if (pname.Length == 0)
    Console.WriteLine("Notepad NÃO está sendo executado");
else
    Console.WriteLine("Notepad está sendo executado");

It is also possible to recover all the running processes

Process[] processos = Process.GetProcesses();

foreach(var p in processos)
{
    Console.WriteLine($"Processo: {p.ProcessName} ID: {p.Id}");
}
  • my compiler is in trouble but I will arrange a time to test so I would like to ask another question in case I would have to put inside a while since I want it to be running in the background and an if Ctrl+d if you want to close it is not even? something else that Process class it belongs to the windows api?

  • The first answer is yes. If you want something to keep checking, you have to make a loop. The second is no, Process is a . NET class, as she does by "under the table" I no longer know how to say.

0

In C#, just use the Diagnostics library of the windows itself.

using System.Diagnostics;

Process[] processo = Process.GetProcessesByName("nomeDoProcesso");
if (processo.Length > 0) Console.WriteLine("Seu processo está rodando!");

Note however, that most processes have the ". exe" at the end, but you should not use this. For example, in the task manager is: "firefox.exe", but in Getprocessesbyname() you should use only "firefox".

Process.GetProcessesByName("firefox");

Already in some file . bat:

@ECHO OFF
TASKLIST /NH /FI "IMAGENAME eq %1" | FIND /I "%1" > NUL
IF %ERRORLEVEL%==0 echo PROCESSO RODANDO

Then just run . bat with the name of the process, and if any process is found it will be printed in cmd.

C:\>teste.bat firefox.exe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.