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'));

相关阅读 >>

Delphi中对进程内存进行读写

使用rad studio为安卓内置的java库

Delphi中操作olevariant、variant和stream

Delphi 实现禁用“任务管理器”

Delphi获取当前计算机所有盘符

Delphi气泡提示

Delphi memo加个prompttext

汇编基础寄存器

firemonkey 做 app 的界面设计方法研究

Delphi 2009 泛型容器单元(generics.collections)[2]: tqueue<t>

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...