delphi 通过窗口标题结束进程  
官方Delphi 学习QQ群: 682628230(三千人)
频道

delphi 通过窗口标题结束进程


uses
Tlhelp32;//注意添加单元文件

function FindWindowByTitle(WindowTitle: string): Hwnd;
  var
    NextHandle: Hwnd;
    NextTitle: array [0 .. 260] of char;
  begin
    NextHandle := GetWindow(Application.Handle, GW_HWNDFIRST);
    while NextHandle > 0 do
    begin
      GetWindowText(NextHandle, NextTitle, 255);
      if Pos(WindowTitle, StrPas(NextTitle)) <> 0 then
      begin
        Result := NextHandle;
        Exit;
      end
      else
        NextHandle := GetWindow(NextHandle, GW_HWNDNEXT);
    end;
    Result := 0;
  end;
  
  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;

//----------------------------------------------------------------------------------------------

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
    GetWindowThreadProcessID(hWindowHandle, @hprocessID);
    if hprocessID <> 0 then
    begin
      processHandle := OpenProcess(PROCESS_TERMINATE or PROCESS_QUERY_INFORMATION,
        False, hprocessID);
      if processHandle <> 0 then
      begin
        TerminateProcess(processHandle, 0);
        CloseHandle(ProcessHandle);
      end;
    end;
  end;
end;


KillTask(FindWindowByTitle('programismi'));
KillProcess(FindWindowByTitle('programismi'));

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.043758869171143 seconds