日期:2014-05-17  浏览次数:20850 次

winform与Javascript的相互调用的问题
Html代码:
 <script language="javascript" type="text/javascript">
 <!-- 提供给C#程序调用的方法 -->
 function messageBox(message)
 {
 alert(message);
 }
 </script>
 winForm代码:
 using System.Security.Permissions;
 [PermissionSet(SecurityAction.Demand, Name = "FullTrust
 [System.Runtime.InteropServices.ComVisibleAttribute(true)]
 public partial class Form1 : Form
 {
 public Form1()
 {
 // 调用JavaScript的messageBox方法,并传入参数
 object[] objects = new object[1];
 objects[0] = "C#访问JavaScript脚本";
 webBrowser1.Document.InvokeScript("messageBox", objects); //这里报错的
 InitializeComponent();
 }
 }
 运行后出现一下错误:
 图片加不上...只能手打了...
  未处理 NullReferenceException
  未将对象引用设置到对象的实例
 
编辑工具是VS2010
 
有知道解决办法的,麻烦帮忙解决一下~谢谢了
 


------解决方案--------------------
// 调用JavaScript的messageBox方法,并传入参数
object[] objects = new object[1];
objects[0] = "C#访问JavaScript脚本";
webBrowser1.Document.InvokeScript("messageBox", objects); //这里报错的
 InitializeComponent();

WebBrowser 必须在Winform初始化之后才有效。
把你的代码(红色部分)放到 Form_Load 事件处理里,或者放在 InitializeComponent 之后。
------解决方案--------------------
还是在webBrowser1_DocumentCompleted事件中保险一些。

因为加载页面是需要时间的。执行laod的时候页面还没加载好。