如何将嵌入资源中的 HTML/JavaScript 加载到 winform Web 浏览器中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9934357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:17:35  来源:igfitidea点击:

How to load HTML/JavaScript from embedded resource into winform web browser

c#javascripthtmlwebbrowser-control

提问by SC28

I want to have some HTML files with JavaScript loaded into the web browser control in a winforms (v2.0) application. During execution, I won't have internet access, so JavaScript and HTML forms will be embedded in he resources.resx file.

我想将一些带有 JavaScript 的 HTML 文件加载到 winforms (v2.0) 应用程序中的 Web 浏览器控件中。在执行期间,我将无法访问 Internet,因此 JavaScript 和 HTML 表单将嵌入到 resources.resx 文件中。

1) how can I load an HTML document out of the resource (analogous to a file:/// operation, but it isn't being loaded from the file system),

1) 如何从资源中加载 HTML 文档(类似于 file:/// 操作,但它不是从文件系统加载的),

2) how would I declare the JavaScript scripts to be loaded? I.e.,

2) 我将如何声明要加载的 JavaScript 脚本?IE,

<script src=resource.jquery.min.js??? ... />

Thanks!

谢谢!

回答by tronbabylove

To load the HTML document, just compile your html file as embedded resource, and then:

要加载 HTML 文档,只需将您的 html 文件编译为嵌入式资源,然后:

WebBrowser browser = new WebBrowser();
browser.DocumentText = Properties.Resources.<your_html_file>;

If you really need to have external .js files, I think you will probably need to make them embedded resources. Then you can read these resources into a string of javascript.

如果您真的需要外部 .js 文件,我认为您可能需要将它们嵌入资源。然后你可以将这些资源读入一串javascript。

string GetResourceString(string scriptFile) 
{ 
    Assembly assembly = Assembly.GetExecutingAssembly(); 
    Stream str = assembly.GetManifestResourceStream(scriptFile); 
    StreamReader sr = new StreamReader(str, Encoding.ASCII));
    return sr.ReadToEnd();
}

(Adapted from a reply on this page)

(改编自本页的回复

From here, look into IHTMLScriptElement. From what I understand, you may be able to use this javascript string and set it as the ITHMLScriptElement's text field. See this question

从这里开始,查看 IHTMLScriptElement。据我了解,您可以使用此 javascript 字符串并将其设置为 ITHMLScriptElement 的文本字段。看到这个问题

Good luck.

祝你好运。

回答by goodfriend0

Here's the file structure.

这是文件结构。

enter image description here

在此处输入图片说明

I had success by doing this:

我通过这样做取得了成功:

Set the properties of the html files in my solution like this:

在我的解决方案中设置 html 文件的属性,如下所示:

Build Action -> Content
Copy to Output Directory -> Copy always

Configure my webBrowser object properties like this:

像这样配置我的 webBrowser 对象属性:

var myAssembly = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
var path = myAssembly.Substring(0, myAssembly.Length - "MyLib.DLL".Length) + "WebViews/prototype/index.html";
webBrowser.Url = new Uri(path);