Delphi,Windows:查找Web浏览器是否正在运行的最佳方法?

1 windows delphi process

查找Web浏览器是否正在运行的最佳方法是什么?

使用Delphi XE2并在Windows上,我需要查找以下是否正在运行以下Web浏览器:

A)Mozilla Firefox B)Apple Safari C)Google Chrome

如果找到,该过程将被终止,因为需要通过修改Web浏览器配置文件以编程方式更改Web浏览器的主页(这是不可能的,或者如果在Web浏览器完成时可能导致不可预测的结果运行).

EnumWindows API函数的输出是否包含处理上述任务所需的足够信息?如果是,那么上述每个Web浏览器的窗口类名称是否记录在何处?如果不是,那么哪种方法最可靠?

TIA.

RRU*_*RUZ 7

在没有用户权限的情况下终止进程不是一个好习惯,而是必须向用户询问是否要终止应用程序(在这种情况下是Web浏览器).

现在回到您的问题,您可以检测是否正在运行的应用程序(webbroser)使用该CreateToolhelp32Snapshot方法检查进程名称(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;
Run Code Online (Sandbox Code Playgroud)

并使用这样的

  IsProcessRunning(['firefox.exe','chrome.exe','safari.exe'])
Run Code Online (Sandbox Code Playgroud)

现在,如果你想要一个更可靠的方法,你可以搜索Window的类名(使用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.
Run Code Online (Sandbox Code Playgroud)