Visit our Sponsor   Visit our Sponsor
delphi3000.com - the free delphi knowledge platform
delphi3000.com - the free delphi knowledge platform
Have a look at your member-status

connecting people's knowledge


  - Recent ArticlesRSS feed for Recent Articles on delphi3000.com
  - List of All Articles
  - Top Viewed Articles
  - Articles (+Attachem.)
  - Articles Of Interest
  - Categories
  - Top Uploader
  - Search
  - Index

  - My Home
  - Submit an Article
  - My Articles
  - My Personal Data
  - My Bookmarks
  - Activities
  - Login/Logout

  - Sign Up
  - Why Sign Up
  - Newsletter

  - Press
  - Advertise

  - Contact
  - Feedback



Community
Borland
ClubeDelphi
Dr. Bob
UK-BUG
Delphi Meetings
Planeta Delphi








Share this article with friendsShare this article with friends
Rate this articleRate this article - to keep the quality of delphi3000.com !
Comment this article or read through previous comments (13)


Kill a taskGo to Misha Moellner's websiteFormat this article printer-friendly!Bookmark function is only available for registered users!
Kill a task using the .exe-name
Product:
Delphi all versions
Category:
System
Skill Level:
Scoring:
Last Update:
01/13/2000
Search Keys:
delphi delphi3000 article borland vcl code-snippet kill task application close remove
Times Scored:
18
Visits:
16474
Uploader: Misha Moellner
Company: sys-it
Reference: http://
 
Question/Problem/Abstract:
How can I kill a task if I only know the .exe name?
Answer:



{ This little function closes all applications with the same
  .exe-name.
  Example: KillTask('notepad.exe');
           KillTask('iexplore.exe'); }

uses
  Tlhelp32, Windows, SysUtils;

function KillTask(ExeFileName: string): integer;
const
  PROCESS_TERMINATE=$0001;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
begin
  result := 0;

  FSnapshotHandle := CreateToolhelp32Snapshot
                     (TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle,
                                 FProcessEntry32);

  while integer(ContinueLoop) <> 0 do
  begin
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
         UpperCase(ExeFileName))
     or (UpperCase(FProcessEntry32.szExeFile) =
         UpperCase(ExeFileName))) then
      Result := Integer(TerminateProcess(OpenProcess(
                        PROCESS_TERMINATE, BOOL(0),
                        FProcessEntry32.th32ProcessID), 0));
    ContinueLoop := Process32Next(FSnapshotHandle,
                                  FProcessEntry32);
  end;

  CloseHandle(FSnapshotHandle);
end;





Please rate this article!
Skill level:
BeginnerExpert

Useful:
No!Very!

Overall rating:
PoorExcellent



Comments to this article
Write a new comment
Liitle problem
    Prahár László (Sep 10 2006 11:42AM)

Some anti-spyware and antivirus program detected this code:

ex.:

NOD32: New Unidentified PE Virus
Spyware Doctor: ........
......
Respond

Another method
    Jonas Laursen (Jun 29 2004 5:00PM)

procedure KillProcess(hWindowHandle: HWND);
var
  hprocessID: INTEGER;
  processHandle: THandle;
  DWResult: DWORD;
begin
  SendMessageTimeout(hWindowHandle, WM_CLOSE, 0, 0,
    SMTO_ABORTIFHUNG or SMTO_NORMAL, 5000, DWResult);

  if isWindow(hWindowHandle) then
  begin
    // PostMessage(hWindowHandle, WM_QUIT, 0, 0);

    { Get the process identifier for the window}
    GetWindowThreadProcessID(hWindowHandle, @hprocessID);
    if hprocessID <> 0 then
    begin
      { Get the process handle }
      processHandle := OpenProcess(PROCESS_TERMINATE or PROCESS_QUERY_INFORMATION,
        False, hprocessID);
      if processHandle <> 0 then
      begin
        { Terminate the process }
        TerminateProcess(processHandle, 0);
        CloseHandle(ProcessHandle);
      end;
    end;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  KillProcess(FindWindow('notepad',nil));
end;

Respond

Incorrect returnvalue
    Gerrit Hulleman (Jun 7 2001 8:33AM)

At the moment I'm trying to use this code to terminate application I start from my own application. The problem is however that the returnvalue of the function FProcessEntry32.szExeFile; sometimes it does not contain the full filename. e.g. 'testapp_server.e' or 'testapp_s.exe', while the actual name is: 'testapp_server.exe'
Perhaps a problem with 8.3 notation, 256 limit of a string or a problem with my develop enviroment windows 2000.
Respond

Under NT/2k
    Donald Leclerc (Jan 19 2001 11:00PM)

Under NT/2k you can't use ToolHelp32 to snoop processes information.  But you can do it with another api interface called PSAPI.DLL.  You can find this DLL under most version of NT and it is always present under 2k.  

Borland provides a unit called PSAPI.pas, which loads all its functions dynamically.  They did it this way, because sometime the PSAPI.DLL is missing, so this way the continue to work, but of course you can't snoop processes information.

The way to obtain information with those API are different from the example in this article, but you can find an article on msdn.microsoft.com "Article ID: Q187913" that describe how to do it.

In brief, you have to Call EnumProcesses() to obtain an array of processes IDs, Call OpenProcess() with PROCESS_QUERY_INFORMATION or PROCESS_VM_READ flags for each process ID to obtain a process handle.  With the handle you must call EnumProcessModules() to obtain an array of module handle for the process and finally obtain your information about process  name with GetModulFileNameEx().


Respond

ExitProcess instead of TerminateProcess ??
    Joze (Jan 19 2001 2:22AM)

This does a "hard" kill.

From the MS help file :
The TerminateProcess function is used to unconditionally cause a process to exit.
Use it only in extreme circumstances. The state of global data maintained by dynamic-link
Libraries (DLLs) may be compromised if TerminateProcess is used rather than ExitProcess.
TerminateProcess causes all threads within a process to terminate, and causes a process
to exit, but DLLs attached to the process are not notified that the process is terminating.

Do you have an example using ExitProcess ??

I tried with:

...
...
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
   UpperCase(ExeFileName)) or
   (UpperCase(FProcessEntry32.szExeFile) =  UpperCase(ExeFileName))) then
      ExitProcess(ExitCode)

...
...

but in this case I don't  terminate process of selected program but
my own program.

Thank you for any help.

Best regards, Joze
Respond

RE: ExitProcess instead of TerminateProcess ??
Ardhea ardhea (Mar 4 2005 11:33PM)

sdrsdsdfgsdfsgdffczxdfgzdfgzdshzsdxdfsgdyseyserysersdfhsdfhxdfsetus fjdfjdydyjsdr
Respond

RE: Kill a Task
    Udo (Nov 9 2000 12:52PM)

Doesn't work with NT4.0 SP5. Problem with Snapshotfile
Respond

RE: RE: Kill a Task
Alberto (Nov 23 2000 4:21AM)

Doesn't work with NT4.0 with SP 6a
Impossible find incoming point Process32Next of the procedure into the DLL Kernel32.dll.
I use Delphi 3.
Respond

RE: RE: Kill a Task
Peter Nagel (Jan 19 2001 1:53AM)

it will NEVER work with ANY Win NT/2k because the whole Toolhelp stuff is only in Win 9x...
Respond

Under NT/2k
Donald Leclerc (Jan 19 2001 10:57PM)

Under NT/2k you can't use ToolHelp32 to snoop processes information.  But you can do it with another api interface called PSAPI.DLL.  You can find this DLL under most version of NT and it is always present under 2k.  

Borland provides a unit called PSAPI.pas, which loads all its functions dynamically.  They did it this way, because sometime the PSAPI.DLL is missing, so this way the continue to work, but of course you can't snoop processes information.

The way to obtain information with those API are different from the example in this article, but you can find an article on msdn.microsoft.com "Article ID: Q187913" that describe how to do it.

In brief, you have to Call EnumProcesses() to obtain an array of processes IDs, Call OpenProcess() with PROCESS_QUERY_INFORMATION or PROCESS_VM_READ flags for each process ID to obtain a process handle.  With the handle you must call EnumProcessModules() to obtain an array of module handle for the process and finally obtain your information about process  name with GetModulFileNameEx().


Respond

RE: Under NT/2k
roma70 roma70 (May 6 2002 11:48AM)

This few lines of code works fine under windows 2000 Professional.
Why ???



Respond

RE: RE: RE: Kill a Task
Ricardo Faustino (Jan 23 2001 6:34AM)

I have Windows 2000 Server installed, and this program is working fine. Thanks a lot to the person who wrote it! It was very usefull!
Respond

RE: RE: RE: RE: Kill a Task
spring mywell (Nov 27 2005 1:33PM)

is there a way to make it recognise the application name like 'notepad.exe' instead of just 'NotePad'
Respond














 
Sign up to consume product discounts for Bronze memberships !

read more


  Visit our Sponsor

 

  Community Ad of
D. Wischnewski
 
   














 







     
  Copyright © 2000 - 2007 delphi3000.com - All rights reserved. Terms of use. || Privacy
delphi3000.com is a service by bluestep.com IT-Services GmbH (Vienna)