查找网络浏览器是否正在运行的最佳方法是什么?
在 Windows 上使用 Delphi XE2,我需要查找以下 Web 浏览器当前是否正在运行:
A) 火狐浏览器 B) 苹果浏览器 C) 谷歌浏览器
如果找到,该进程将被终止,因为需要通过修改网络浏览器配置文件以编程方式更改网络浏览器的主页(这是不可能的,或者如果在 web 时完成可能会导致不可预测的结果) -浏览器正在运行)。
EnumWindows API 函数的输出是否包含处理上述任务所需的足够信息?如果是,那么是否在任何地方记录了上述每个网络浏览器的窗口类名称?如果不是,那么哪种方法最可靠?
TIA。
最佳答案
未经用户许可终止进程不是好的做法,相反,您必须询问用户是否要终止应用程序(在本例中为网络浏览器)。
现在回到您的问题,您可以使用 CreateToolhelp32Snapshot 检测应用程序 (webbroser) 是否正在运行检查进程名称(firefox.exe、chrome.exe、safari.exe)方法。
uses
Windows,
tlhelp32,
SysUtils;
function IsProcessRunning(const ListProcess: Array of string): boolean;
var
hSnapshot : THandle;
lppe : TProcessEntry32;
I : Integer;
begin
result:=false;
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if hSnapshot <> INVALID_HANDLE_VALUE then
try
lppe.dwSize := SizeOf(lppe);
if Process32First(hSnapshot, lppe) then
repeat
for I := Low(ListProcess) to High(ListProcess) do
if SameText(lppe.szExeFile, ListProcess[i]) then
Exit(True);
until not Process32Next(hSnapshot, lppe);
finally
CloseHandle(hSnapshot);
end;
end;
然后像这样使用
IsProcessRunning(['firefox.exe','chrome.exe','safari.exe'])
现在,如果你想要一种更可靠的方法,你可以搜索窗口的类名(使用 FindWindowEx 方法),然后搜索句柄的进程所有者的 PID(使用 GetWindowThreadProcessId ),从这里你可以使用进程的PID来解析exe的名称。
{$APPTYPE CONSOLE}
uses
Windows,
tlhelp32,
SysUtils;
function GetProcessName(const th32ProcessID: DWORD): string;
var
hSnapshot : THandle;
lppe : TProcessEntry32;
begin
result:='';
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if hSnapshot <> INVALID_HANDLE_VALUE then
try
lppe.dwSize := SizeOf(lppe);
if Process32First(hSnapshot, lppe) then
repeat
if lppe.th32ProcessID=th32ProcessID then
Exit(lppe.szExeFile);
until not Process32Next(hSnapshot, lppe);
finally
CloseHandle(hSnapshot);
end;
end;
function IsWebBrowserRunning(const ClassName, ExeName :string) : Boolean;
var
hWindow : THandle;
dwProcessId: DWORD;
begin
result:=False;
hWindow:= FindWindowEx(0, 0, PChar(ClassName), nil);
if hWindow<>0 then
begin
dwProcessId:=0;
GetWindowThreadProcessId(hWindow, dwProcessId);
if dwProcessId>0 then
exit(Sametext(GetProcessName(dwProcessId),ExeName));
end;
end;
begin
try
if IsWebBrowserRunning('MozillaWindowClass','firefox.exe') then
Writeln('Firefox is Running');
if IsWebBrowserRunning('{1C03B488-D53B-4a81-97F8-754559640193}','safari.exe') then
Writeln('Safari is Running');
if IsWebBrowserRunning('Chrome_WidgetWin_1','chrome.exe') then
Writeln('Chrome is Running');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
readln;
end.
关于windows - 德尔福,Windows : Best way to find whether web-browser is running?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514428/