有谁知道是否可以通过 WebBrowser 组件中的链接打开文件系统中的文件?我正在编写一个小报告工具,在其中我在 WebBrowser 组件中以 HTML 格式显示摘要,并带有指向更详分割析的链接,该分析在磁盘上保存为 Excel 文件。
我希望用户能够在网络浏览器中单击该链接(目前只是一个以 file://path.xls 作为目标的标准 href 标记)并得到打开文件的提示。 如果我在 IE 中打开我的页面,这有效,但在 WebBrowser 控件(C# Windows 窗体、.Net 2.0)中没有任何反应。
我不知道我是否需要一些额外的权限/信任或类似的东西 - 有没有人成功地做到了这一点,或者有人可以建议如何调试它?
最佳答案
我还测试了 Ross 的解决方案,它对我也很有效。
但这里有另一种方法,而不是使用弹出对话框要求您下载、打开或取消下载的内置功能,您可以在您的应用程序(而不是 HTML 页面)中使用您自己的 C# 代码直接打开文件(或者做其他事情)。
根据 Microsoft MSDN示例:
using System;
using System.Windows.Forms;
using System.Security.Permissions;
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
private WebBrowser webBrowser1 = new WebBrowser();
private Button button1 = new Button();
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
public Form1()
{
button1.Text = "call script code from client code";
button1.Dock = DockStyle.Top;
button1.Click += new EventHandler(button1_Click);
webBrowser1.Dock = DockStyle.Fill;
Controls.Add(webBrowser1);
Controls.Add(button1);
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
// Uncomment the following line when you are finished debugging.
//webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"onclick=\"window.external.Test('called from script code')\">" +
"call client code from script code</button>" +
"</body></html>";
}
public void Test(String message)
{
MessageBox.Show(message, "client code");
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("test",
new String[] { "called from client code" });
}
}
关于.net - 从 WebBrowser 控件中打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/325512/