如何使用本地文件的URL(带空格和#)启动默认浏览器?德尔菲 [英] How to start default browser with a URL(with spaces and #) for a local file? Delphi
问题描述
我想在默认浏览器中打开本地HTML文件。
I want to open a local HTML file in the default browser.
例如:
默认浏览器为Mozilla Firefox。
For example: Default Browser is Mozilla Firefox.
要打开的文件:C:\我的自定义路径\新建文件夹\AFile.htm
The file to be opened: C:\My Custom Path\New Folder\AFile.htm
请注意,路径中有空格。根据条件,我想在URL末尾附加一个ID。
Please note the path has spaces. Depending on conditions I want to append an Id at the end of the URL.
最终URL为C:\我的自定义路径\新建文件夹FileAFile.htm #12345
Final URL is C:\My Custom Path\New Folder\AFile.htm#12345
如果我手动打开浏览器,并粘贴URL C:\我的自定义路径\新文件夹\AFile.htm#12345。
If I open the browser manually, and paste the URL "C:\My Custom Path\New Folder\AFile.htm#12345".
工作正常。无法找到通过代码执行此操作的最佳方法。
It works fine. Unable to find the best way to do this through code.
推荐答案
ShellExecute / Ex()
不能直接在URL中使用 open
动词和锚(#
) 。即使您使用 file://
协议,锚也会被忽略。
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.
最好的方法是获取默认浏览器的路径,您可以使用 FindExecutable
,然后执行它并将URL作为参数传递。
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;
编辑:看起来像 file:///
URI方案很重要(例如 file.html?param = foo#bar
),否则?
被转义为%3F
(在Chrome中测试)
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)
这篇关于如何使用本地文件的URL(带空格和#)启动默认浏览器?德尔菲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!