原文:http://www.cnblogs.com/del/archive/2008/03/10/1098502.html
//声明: {返回进程的句柄}
OpenProcess(
dwDesiredAccess: DWORD; {访问选项}
bInheritHandle: BOOL; {能否继承; True 表示能用 CreateProcess 继承句柄创建新进程}
dwProcessId: DWORD {指定进程 ID}
): THandle; {成功会返回进程句柄; 失败返回 0} //dwDesiredAccess 可选值:
PROCESS_TERMINATE = $0001; {允许 TerminateProcess 使用进程句柄来关闭进程}
PROCESS_CREATE_THREAD = $0002; {允许 CreateRemoteThread 使用进程句柄来创建线程}
PROCESS_VM_OPERATION = $0008; {允许 VirtualProtectEx 使用进程句柄来改变进程的虚拟内存}
PROCESS_VM_READ = $0010; {允许 ReadProcessMemory 使用进程句柄从进程的虚拟内存中读取数据}
PROCESS_VM_WRITE = $0020; {允许 WriteProcessMemory 使用进程句柄向进程的虚拟内存中写入数据}
PROCESS_DUP_HANDLE = $0040; {允许 DuplicateHandle 把进程句柄当作源句柄或目标句柄进行复制}
PROCESS_CREATE_PROCESS = $0080; {默认值}
PROCESS_SET_QUOTA = $0100; {允许 SetProcessWorkingSetSize 使用进程句柄来来设置虚拟内存的上限值}
PROCESS_SET_INFORMATION = $0200; {允许 SetPriorityClass 使用进程句柄来设置进程优先级}
PROCESS_QUERY_INFORMATION = $0400; {允许 GetExitCodeProcess 或 GetPriorityClass 通过进程句柄读取进程信息}
SYNCHRONIZE = $00100000; {允许任何等待的函数使用进程句柄}
PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $FFF); {允许所有权限}
{获取指定进程的退出码}
GetExitCodeProcess(
hProcess: THandle; {进程句柄}
var lpExitCode: DWORD {接收退出码}
): BOOL; {}
{强制结束(其他)进程}
TerminateProcess(
hProcess: THandle; {进程句柄}
uExitCode: UINT {退出码}
): BOOL; {} //提示: 关闭其他程序一般应该是向其主窗口发送 WM_CLOSE 消息, 不行再用这个, 因为它不能关闭其关联的 DLL.
//举例(强行关闭 OICQ 的办法):
unit Unit1; interface uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls; type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end; var
Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject);
var
id: Cardinal;
wh: HWND;
ph: THandle;
ExitCode: DWORD;
begin
wh := FindWindow('#32770', nil);
GetWindowThreadProcessId(wh, id);
ph := OpenProcess(PROCESS_TERMINATE, False, id);
GetExitCodeProcess(ph, ExitCode);
TerminateProcess(ph, ExitCode);
end; end.
提示: #32770 是提前知道的类名, 获取方法可参见:
http://www.cnblogs.com/del/archive/2008/03/09/1097942.html
GetWindowThreadProcessId 函数请参见: http://www.cnblogs.com/del/archive/2008/03/10/1098475.html