Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / system

Killing a process using MainWindowTitle

5.00/5 (2 votes)
27 Feb 2013CPOL2 min read 24K   473  
Using the MainWindowTitle property to close a running program by killing the associated process.

Introduction  

I'm a Fox programmer, I use the VFP9 editor for my everyday programming work. I always run two sessions of vfp9.exe, one for the development environment and the other for testing. I write code, run the application, trace the written code, and see if it works and check if there is a problem. Many times I reach a point where I have to kill the vfp9.exe process from the list of processes when the program is trapped in an not so trivial error that can not be ignored.

The Problem

The problem is that I do not need to open the Task Manager every time and kill the process of the testing environment, so I created a DOS batch program file to do that job using the "TASKKILL" command. But the only information I know is the exe name, i.e., vfp9.exe, and I have no information about the process ID # to kill a specific process, not all instances, so I always issue the command.

>taskkill  /IM vfp9.exe

which kills all the running instances. I needed to only kill the stuck testing vfp9.exe instance, not the development one.

Image 1

The suggested solution

I discovered a property in the class System.Diagnostics.Process called MainWindowTitle. I found that I can use it to kill only the instance I need.

First I ran the testing instance with a specific caption that distinguishes it from another one, say that contains the word 'test'.

Image 2

Then in my C# program I define an array of all running processes  as follows:

C#
using System.Diagnostics
... 
Process[] processes = Process.GetProcesses();

I then issue a foreach loop to check the process I intend to close:

C#
foreach (Process pr in processes)            { 
  if (pr.ProcessName.ToLower().Contains("vfp"))
    if (pr.MainWindowTitle.ToLower().Contains("test"))
      pr.CloseMainWindow();
}

Here I first check if the process name contains "vfp", and that its title contains "test", then I close it, and that is the whole idea.

I developed the attached source code more generally to kill any process with any title. It gets the text that is to be checked in the process name and the process window title from a text file with the same name as the exe file. To achieve this target I create a text file with the same name as the exe name and insert in it the line "vfp|test". When the program runs, it gets the two strings separated by the pipe "|" into a list and then for each process, loops over  this list doing the same checks as above. Here is the full code:

C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace KillProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            string txtFl = System.Reflection.Assembly.GetEntryAssembly().GetName().Name+".txt";
            List<string> getKilled = new List<string>();
            if (File.Exists(txtFl))
            {
                //read file lines to the list
                using (StreamReader sr = File.OpenText(txtFl))
                {
                    string s;
                    while ((s = sr.ReadLine()) != null)
                    {
                        // in case that the pipe does not exist in the line to always keep the word 
                        // contained in the title in the even index in the list
                        s = (s.Contains("|") ? s : s + "|"); 
                        getKilled.AddRange(s.ToLower().Split('|'));
                    }
                }
            }
            if (getKilled.Count == 0) return; //the file is not found or empty
            // define the processes array, loop over it 
            Process[] processes = Process.GetProcesses();
            foreach (Process pr in processes)
                for (int i = 0; i < getKilled.Count; i += 2)
                    if (!string.IsNullOrEmpty(getKilled[i]) && !string.IsNullOrEmpty(getKilled[i + 1]))
                        if (pr.ProcessName.ToLower().Contains(getKilled[i]))
                            if (pr.MainWindowTitle.ToLower().Contains(getKilled[i + 1]))
                                pr.CloseMainWindow();
        }
    }
}

Conclusion 

We can add more lines to the text file that has the same name as the program exe name, but be careful when filling up this file to not close critical programs.

To use this program practically, I created a shortcut of the exe KillProcess.exe on my desktop and associated it with a shortcut key combination to easily call the program. This program has no interface.

I hope you find it useful.

License

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