2010年6月27日 星期日

第二次運行時自動關閉程式如何實現

以下做法可以實現:一支程式,第一次可正常運行,重複運行時,不但不能運行,還把第一次運行的程式關閉
uses Tlhelp32;

function FindProcess(AFileName: string): boolean;
var
hSnapshot: THandle;
lppe: TProcessEntry32;
Found: Boolean;
KillHandle: THandle;
begin
Result :=False;
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
lppe.dwSize := SizeOf(TProcessEntry32);
Found := Process32First(hSnapshot, lppe);
while Found do
begin
if ((UpperCase(ExtractFileName(lppe.szExeFile))=UpperCase(AFileName)) or (UpperCase(lppe.szExeFile )=UpperCase(AFileName))) then
begin
Result :=True;
end;
Found := Process32Next(hSnapshot, lppe);
end;
end;


procedure EndProcess(AFileName: string);
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOL;
FSnapShotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
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(AFileName)) or (UpperCase(FProcessEntry32.szExeFile )=UpperCase(AFileName))) then
TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0),FProcessEntry32.th32ProcessID), 0);
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
if FindProcess('notepad.exe') then
begin
EndProcess('notepad.exe');
end;
end;

沒有留言: