delphi 結束進程

來源:互聯網
上載者:User

在網上搜了一下delphi結束進程的代碼,發現當要結束的進程名是當前的進程並且該程式開了多個的話,會因為當前進程在結束其他進程前把自己關掉而不能結束所有同名的進程,所以修改了一下:

註:TProcessEntry32 需要引用單元 uses TLHelp32;

 

function killProcess(iProcessName:string):boolean;
var
  HandleSnap:THandle;//用於獲得進程列表
  killHandle:THandle;
  processEntry:TProcessEntry32;//用於尋找進程
  found:boolean;
  count:integer;
  selfProcessID:cardinal;

begin
  HandleSnap:=CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0);//獲得系統進程列表
  processEntry.dwSize:=sizeof(TProcessEntry32);/在調用Process32First API之前,需要初始化lppe記錄的大小

  selfProcessID:=getCurrentProcessID();//獲得當前Delphi應用程式的進程ID

  count:=0;
  found:=process32First(HandleSnap,processEntry);//將進程列表的第一個進程資訊讀入記錄中
  while(found)do
  begin
    if((uppercase(extractFileName(processEntry.szExeFile))=upperCase(iProcessName))
      or(uppercase(processEntry.szExeFile)=upperCase(iProcessName)))then
    begin
      if(processEntry.th32ProcessID<>selfProcessID)then//如果進程是當前進程,則不結束
      begin
        killHandle:=OpenProcess(PROCESS_TERMINATE, False, processEntry.th32ProcessID);
        TerminateProcess(killHandle,0);
      end;
      inc(count);
    end;
    found:=process32Next(HandleSnap,processEntry);//將進程列表的下一個進程資訊讀入記錄中
  end;

  closeHandle(handleSnap);

  //搜尋完所有進程後,如果要結束的進程名與當前應用程式的名字一樣,則結束當前進程
  if(uppercase(iProcessName)=uppercase(extractFileName(application.ExeName)))then
  begin
    killHandle:=OpenProcess(PROCESS_TERMINATE, False, selfProcessID);
    TerminateProcess(killHandle,0);
  end;
end;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.