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

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

    I ended up doing this. I get the default browser, and used the CreateProcess API to launch the browser with my custom URL. Notice, I add the 'file:///' in the beginning and also surround the string with double quotes.

    function GetDefaultBrowser(): String;
    var
        ExecName: array[0..MAX_PATH] of Char;
        FHandle: THandle;
        MyPath: String;
    begin
        Result := '';
        MyPath := small.GetTempPath;
        FHandle := System.SysUtils.FileCreate(MyPath + 'AFile.htm');
    
        if FHandle <> INVALID_HANDLE_VALUE then
        begin
            FillChar(ExecName, Length(ExecName), #0);
            if FindExecutable('AFile.htm', PChar(MyPath), ExecName) > 32 then
                Result := ExecName;
            System.SysUtils.FileClose(FHandle);
            System.SysUtils.DeleteFile(MyPath + 'AFile.htm');
        end;
    end;
    
    
    procedure LaunchHTMLPage(NumberToAppend : string);
    var
        Start: TStartupInfo;
        Process: TProcessInformation;
        FileNameString, AppPathAndName, AppPathOnly: string;
    begin
        AppPathAndName := GetDefaultBrowser ;
    
        //Break the AppPathAndName and get the path name to use later
    
        //I am adding double quotes in the path name to escape the spaces and the '#'
        FileNameString := AnsiQuotedStr('file:///' + Application.HelpFile + '#' + NumberToAppend, '"');
        AppPathAndName := AppPathAndName + ' ' + FileNameString;
        FillChar(Start, SizeOf(StartUpInfo), #0);
        FillChar(Process, SizeOf(TProcessInformation), #0);
    
        CreateProcess(nil, PChar(AppPathAndName), nil, nil, false, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, PChar(AppPathOnly), StartUpInfo, ProcessInfo);
    
    end;
    

提交回复
热议问题