2
votes

I need to either bring front browser window if it is already running or launch the browser from my application. I'm now using ShellExecute to open a new browser, but it will eventually create many browser instances or tabs. So how to check if the browser is already running and switch the application to browser?

I'm currently using this:

ShellExecute(Handle, 'open', URL, nil, nil, SW_SHOWNORMAL);
3

3 Answers

3
votes
function EnumProcess(Handle: HWND; lParam: Integer): BOOL; stdcall;
var
  PID : Cardinal;
  Title : String;
begin
  If Handle = NULL Then
    begin
    Result := False;
  end
  Else
    begin
    GetWindowThreadProcessID(Handle,PID);
    If PID = lParam Then
    begin
      SetForegroundWindow(Handle);
      Result := False;
    end
    else
      Result := True;
  end;
end;

procedure TMainForm.StartBrowser();
var
  h: HWND;
  S: tagPROCESSENTRY32;
  bFound: boolean;
begin
  h := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  S.dwSize := SizeOf(tagPROCESSENTRY32);
  Process32First(h, S);
  bFound := false;
  while Process32Next(h, S) do
  begin
    if Pos('iexplore', LowerCase(S.szExeFile)) <> 0 then
    begin
      bFound := true;
      EnumWindows(@EnumProcess,Integer(Pointer(S.th32ProcessID)));
    end;
  end;
  if (not bFound) then
    ShellExecute(Handle, 'open', 'http://www.stackoverflow.com', nil, nil,         SW_SHOWNORMAL);
end;
1
votes

The way you're doing it is the way to open the default browser. The issue with that is it appears both IE and Firefox will always reopen the document instead of bringing the relevant tab to the front.

I thought you might be able to do browser-specific things with command-line switches. In that case, you should get the default browser from HKEY_CLASSES_ROOT\HTTP\shell\open\command.

Unfortunately, neither of the two major browsers have a switch to only open a URL that is not already opened. (IE switches here, Firefox switches here). Also, in the days of non-tabbed browsing I would have encouraged you to look at EnumWindows to find the relevant session, but that doesn't work anymore AFAIK.

My advice:

  1. Check default browser
  2. For IE, use Icebob's code. Also use this or your current ShellExecute code for browsers you don't explicitly support.
  3. For Firefox, check out developer.mozilla.org. There is bound to be some way.
  4. Ditto for webkit (Chrome, Safari) and Opera.

Or live with the duplicates. In that case, your ShellExecute code is perfect.

I would probably live with the duplicates.

0
votes

Your best bet is probably to use DDE to find the existing window.

Also, hardcoding the open verb is not a good idea, its better to pass NULL/nil