gpt4 book ai didi

delphi - 仅具有进程ID时关闭主应用程序窗口的问题

转载 作者:行者123 更新时间:2023-12-03 19:44:15 25 4
gpt4 key购买 nike

我有流程的ID。此过程是一个具有主窗口的应用程序。
我正在尝试通过将WM_CLOSE发送到其主窗口来关闭此应用程序。
我正在使用EnumWindows搜索其主窗口。

问题是,我尝试关闭的该应用程序并不总是关闭。
它是多线程应用程序。当我使用下面介绍的相同方法时,记事本和Calc总是关闭。但是我不确定它是否正常运行,因为即使对于Calc.exe,它也会使我将许多句柄返回到同一窗口。

线程是否有可能获取窗口句柄,然后该句柄以某种方式损坏?或者,也许我不应该在回调中使用GetWindowThreadProcessId(hHwnd,pPid)而是其他函数?

我没有主意,不胜感激。谢谢。

程式码片段:

unit Unit22;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm22 = class(TForm)
edtprocID: TEdit;
lblEnterProcessID: TLabel;
btnCloseProcessWindow: TButton;
lblStatus: TLabel;
procedure btnCloseProcessWindowClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

type
THandleAndHWND = record
ProcID: THandle;
WindowHandle: HWND;
end;

var
Form22: TForm22;

var
HandleAndHWNDArray: array of THandleAndHWND;
HandeIndex, lp: Integer;

implementation

{$R *.dfm}

function EnumProcess(hHwnd: HWND; lParam : integer): boolean; stdcall;
var
pPid : DWORD;
begin
//if the returned value in null the
//callback has failed, so set to false and exit.
if (hHwnd=0) then
begin
result := false;
end else
begin
GetWindowThreadProcessId(hHwnd,pPid);
Inc(HandeIndex);
HandleAndHWNDArray[HandeIndex].ProcID := pPid;
HandleAndHWNDArray[HandeIndex].WindowHandle := hHwnd;
Result := true;
end;

end;

procedure TForm22.btnCloseProcessWindowClick(Sender: TObject);
var
ProcID: Cardinal;
i, LastError: Integer;
begin
HandeIndex := -1;
ProcID := StrToInt(edtprocID.Text);

SetLength(HandleAndHWNDArray, 3000);
EnumWindows(@EnumProcess,lp);

for i := 0 to HandeIndex do //After EnumWindows HandleIndex is above 500 despite the fact that I have like 10 openned windows max
begin //That means that EnumWindows was called 500 times?
if HandleAndHWNDArray[i].ProcID = ProcID then //search for process equal to procces ID given by the user
begin
//if we have a processID then we have a handle to its main window
if PostMessage(HandleAndHWNDArray[i].WindowHandle, WM_CLOSE, 0, 0) then
begin
lblStatus.Caption := 'message posted!';
end else
begin
LastError := GetLastError;
lblStatus.Caption := Format('Error: [%d] ' + SysErrorMessage(LastError), [LastError]);
end;
Exit;
end;
end;

end;

end.

最佳答案

在此知识库文章here中,了解如何尽可能干净地关闭另一个应用程序。到目前为止,您做得对。文章建议你


首先将WM_CLOSE发布到应用程序的所有窗口(因为您无法确定哪个是主要窗口)。
等待超时,如果超时已过去
使用TerminateProcess终止应用程序


我同意。

关于delphi - 仅具有进程ID时关闭主应用程序窗口的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6909775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com