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

后端 未结 6 1267
天涯浪人
天涯浪人 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:25

    Here is my implementation that supports all common web browsers and Microsoft Edge (Windows Store App).
    It refers to the issues with queries (?) and fragments (#) in the URI and the issue with file:/// protocol in combination with the Edge browser.
    (I use it for HTML output of "Flare" software, that's why the "help" in the naming of variables)

    // AHelpFileName := 'C:\temp\Default.htm';
    // AHelpID := '123';
    
    procedure TSomeClass.OpenHelp(const AHelpFileName, AHelpID: string);
    var
      URL: string;
      BrowserPath, FileName, Parameters: PWideChar;
    begin
      URL := Format('file:///%s', [AHelpFileName]);
      if AHelpID <> '' then
        URL := Format('%s#cshid=%s', [URL, AHelpID])
    
      URL := StringReplace(URL, '\', '/', [rfReplaceAll]);
      URL := StringReplace(URL, ' ', '%20', [rfReplaceAll]);
    
      BrowserPath := StrAlloc(MAX_PATH);
      Parameters := nil;
    
      if FindExecutable(PWideChar(AHelpFileName), nil, BrowserPath) > 32 then
      begin
        Parameters := PWideChar(URL);
    
        if SameText(ExtractFileName(BrowserPath), 'LaunchWinApp.exe') then
          // Default browser is a Windows Store App (and most likely it is Edge)
          FileName := 'shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge'
        else
          // IE, Chrome, Firefox, Opera, Vivaldi, ...
          FileName := BrowserPath;
      end
      else
        FileName := PWideChar(URL);
    
      ShellExecute(0, nil, FileName, Parameters, nil, SW_SHOWNORMAL);
    end;
    

提交回复
热议问题