How do I check, while my program is running, if a particular software is opened by the user?
How do I check, while my program is running, if a particular software is opened by the user?
Filtering for window titles
If you're not sure what the application name is, and you want to, for example, use the Contains
method in the name of the main window, you could enumerate all running processes, and check which ones meet your criteria.
while (true)
{
var isOpen = Process.GetProcesses().Any(p =>
p.MainWindowTitle.Contains("Microsoft"));
if (isOpen)
Console.WriteLine("Aplicação com titulo 'Microsoft' está aberta");
Thread.Sleep(1000);
}
If you know the name of the application, you can use the ProcessName
property instead of the window name.
Knowing the name of a process
It is very easy to know the name of the processes, just use the Windows Task Manager (Ctrl + Shift + Esc), and go to the Processes tab ... the name is usually the first column that appears, but not include the extension. If an application is called devenv.exe
, just use "devenv" as the name in your code:
while (true)
{
var isOpen = Process.GetProcesses().Any(p =>
p.ProcessName == "devenv");
if (isOpen)
Console.WriteLine("Aplicação com titulo 'Microsoft' está aberta");
Thread.Sleep(1000);
}
One solution is to check the processes that are open in a thread and look for which particular application you are checking.
A very simple example to check when the user opened the Windows calculator (whose process name is calc
):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Process[] pname = Process.GetProcessesByName("calc");
if (pname.Length != 0)
{
Console.WriteLine("A calculadora foi aberta as " + DateTime.Now.ToString("HH:mm:ss tt"));
break;
}
else
{
Console.WriteLine("A calculadora ainda não foi aberta.");
}
Thread.Sleep(200);
}
Console.ReadKey();
}
}
}
Note that Process.GetProcessesByName()
is in System.Diagnostics
and Thread.Sleep()
is in System.Threading
. The Thread.Sleep(200)
(in this case) was to give the CPU a break (it is not critical to check if the calculator was opened every ms).