一個根據進程名得到PID的函數,原先是把進程名直接寫在函數裏面的
function FindProcessName:THandle;
………
if ansiCompareText(ExtractFileName(lppe.szExefile),'notepad.exe') = 0 then
我把它改成帶參數的函數,把進程名作爲參數寫在函數裏了。
function FindProcessName(exeName:string):THandle;
……
if ansiCompareText(ExtractFileName(lppe.szExefile),exeName) = 0 then
結果函數中的found永遠是false,暈倒,百思不得其解
最後抱着試試看的想法,把參數exeName的類型改爲pchar,結果成功了。鬱悶啊,如果說是pchar和string類型有別,那也不能在還沒有運行到if語句的時候就會有差別啊( 如果參數爲string類型時, found := process32first(sshandle, lppe);這一句得到的結果就是false了,但參數是在下面的循環中才用到的啊)
可以正確運行的函數是,(本文爲delphi7中測試的結果)
function FindProcessName(exeName:pchar):THandle;
var
lppe: tprocessentry32;
sshandle: thandle;
found: boolean;
begin
result:=0;
sshandle := createtoolhelp32snapshot(TH32CS_SNAPALL, 0);
found := process32first(sshandle, lppe);
while found do
begin
if ansiCompareText(ExtractFileName(lppe.szExefile),exeName) = 0 then
begin
result:=lppe.th32ProcessID;
break;
end;
found := process32next(sshandle, lppe); {檢索下一個進程}
end;
CloseHandle(sshandle);
end;
補記:下午再測試時卻發覺又出了同樣的問題,看來是修改的對象錯誤了,不關pchar的事。google了不少文章,發現有一篇文章提到:tprocessentry32的dwsize必須要初始化後process32first纔可以使用,否則可能出錯,於是加上了一句 lppe.dwSize:=sizeof(PROCESSENTRY32); 這次似乎是真的起作用了。現下使用正常。