How to know when the user opened an application?

Asked

Viewed 2,496 times

7

How do I check, while my program is running, if a particular software is opened by the user?

  • 1

    In the English version you can find a solution. Please see the link http://stackoverflow.com/a/967668/47733

2 answers

7

One solution is to check the processes that are open in a thread and find out which application you are checking for.

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 a break to the CPU (it is not critical to check if the calculator was opened every ms).

7


Filtering by window titles

If you don’t know what the name of the application is, and want to use the method Contains in the name of the main window, could list all running processes, and verify which of them 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 property ProcessName instead of the window name.

How to know 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 without including 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);
}
  • That’s right, thank you!

Browser other questions tagged

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