How to start default browser with a URL(with spaces and #) for a local file? Delphi

后端 未结 6 1266
天涯浪人
天涯浪人 2021-01-21 06:15

I want to open a local HTML file in the default browser.

For example: Default Browser is Mozilla Firefox.

The file to be opened: C:\\My Custom Path\\New Folde

6条回答
  •  孤独总比滥情好
    2021-01-21 06:36

    ShellExecute/Ex() won't work directly using "open" verb with the anchor (#) in the URL. even if you use file:// protocol the anchor will be omitted.

    The best way is to get the path for the default browser, you can use FindExecutable, and then execute it and pass the URL as a parameter.

    uses
      ShellAPI;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      Res: HINST;
      Buffer: array[0..MAX_PATH] of Char;
      SEInfo: TShellExecuteInfo;
      HtmlFile, Anchor: string;
    begin
      HtmlFile := 'd:\1 - Copy.html';
      Anchor := '#123';
    
      FillChar(Buffer, SizeOf(Buffer), 0);
      Res := FindExecutable(PChar(HtmlFile), nil, Buffer);
      if Res <= 32 then
        raise Exception.Create(SysErrorMessage(Res));
    
      FillChar(SEInfo, SizeOf(SEInfo), 0);
      SEInfo.cbSize := SizeOf(SEInfo);
      with SEInfo do
      begin        
        lpFile := PChar(string(Buffer));
        lpParameters := PChar(Format('"file:///%s"', [HtmlFile + Anchor]));
        nShow := SW_SHOWNORMAL;
        fMask := SEE_MASK_FLAG_NO_UI; // Do not display an error message box if an error occurs.
      end;
      if not ShellExecuteEx(@SEInfo) then
        RaiseLastOSError;
    end;
    

    EDIT: Looks like the file:/// URI scheme is important in cases where the URL includes query string parameters (e.g file.html?param=foo#bar) or else the ? is escaped to %3F (tested in Chrome)

提交回复
热议问题