在Delphi中如何关闭一个没有窗口的外部程序...(100分)

  • 主题发起人 主题发起人 ledo
  • 开始时间 开始时间
L

ledo

Unregistered / Unconfirmed
GUEST, unregistred user!
就是按下‘CTRL+ALT+DEL’可以看到,而没有窗口的运行中的程序。
 
Use EnumProcesses under Win2000,
Use Process32First() and Process32Next() under Win98.
 
Sorry, Use above functions to find the Thread, and use CloseHandle()
to "Kill" it.
 
HWndCalculator = FindWindow(NULL, "超級解霸-MMX 5.5")
// close the exist Calculator
if (HWndCalculator !=0 )
SendMessage(HWndCalculator, WM_CLOSE, 0, 0);
 
看我的:D

1、首先在两个工程之间声明消息
initialization
WM_OURMESSAGE := RegisterWindowMessage('XXX');

2、下面将被关闭的程序称为B程序,用来关闭它的程序称为A程序;
3、然后在A程序中监听消息wm_ourmessage,并设定条件为其值>434(条件可视情况再改);
4、B程序中向A发消息:
SendMessage(hwnd_broadcast,wm_ourmessage,435,0);
5、A程序判断435>434,则执行关闭操作/其它操作;
6、A程序相关部分如下:

procedure Tfrm_XXX.N0305Click(Sender: TObject);
var
lpMsgBuf : String;
SI: TStartupInfo;
PI: TProcessInformation;
begin
//如果进程存在则关闭它
if bResult = true then
begin
SendMessage(hwnd_broadcast,wm_ourmessage,435,0);
bResult := false;
end;
//进程不存在
if bResult = false then
begin
FillChar(SI, SizeOf(SI), 0);
SI.cb := SizeOf(SI);
bResult := CreateProcess(
'XXX.exe',
pchar('1 'aaa.txt'),
nil,
nil, //LPSECURITY_ATTRIBUTES lpThreadAttributes, // pointer to thread security attributes
True, //BOOL bInheritHandles, // handle inheritance flag
CREATE_NEW_CONSOLE, //DWORD dwCreationFlags, // creation flags
nil, //LPVOID lpEnvironment, // pointer to new environment block
nil, //LPCTSTR lpCurrentDirectory, // pointer to current directory name
SI, // pointer to STARTUPINFO
PI // pointer to PROCESS_INFORMATION
);
//创建失败;
if ( bResult = FALSE ) Then
Begin
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER or
FORMAT_MESSAGE_FROM_SYSTEM or
FORMAT_MESSAGE_IGNORE_INSERTS,
nil,
GetLastError(),
0,
@lpMsgBuf,
0,
nil
);
End;
end;
end;
 
我的方法同duckstar的差不多,但我用TerminateProcess(),
因为发现有时候用CloseHandel不管用。
 
没这么麻烦:

Uses tlhelp32;

Function TForm1.KillTask(FileName:String):integer;
var
CLoop:BOOL;
KHandle:THandle;
Process:TProcessEntry32;
const
PROCESS_TERMINATE=$0001;
begin
KHandle:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
Process.dwSize:=Sizeof(Process);
CLoop:=Process32First(KHandle,Process);
while integer(CLoop)<>0 do
begin
if
((UpperCase(ExtractFileName(Process.szExeFile))=UpperCase(FileName))
or (UpperCase(Process.szExeFile)=UpperCase(FileName)))
then

Result:=Integer(TerminateProcess(OpenProcess(PROCESS_TERMINATE,BOOL(0),

Process.th32ProcessID),0));
CLoop:=Process32Next(KHandle,Process);
end;
CloseHandle(KHandle);
end;
 
接受答案了.
 
后退
顶部