如果页面中有iframe那么DocumentComplete事件会多次触发private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (string.Compare(e.Url.ToString(), url, true) != 0) return; // 判断一下是否为期望的url
    //...
}

解决方案 »

  1.   

    谢谢 zswang 的答复。我的问题在目标程序(已编译的EXE程序)的Webbrowser控件载入网页并触发 SHDocVw.DWebBrowserEvents2_DocumentCompleteEventHandler 事件时,为什么 IHTMLDocument2 对象无法获取 parentWindow ?再参考了网上的资料后得知 Webbrowser 控件只能在STA模式工作,但我不知道该如何使我的程序或DocumentComplete事件的响应方法工作在STA模式参考资料:
    http://social.msdn.microsoft.com/Forums/en/ieextensiondevelopment/thread/1212c336-95a6-4f2a-8829-197fb3edf7a8
      

  2.   

    有谁能帮忙回答一下这个问题吗?已经困惑了我两个星期了一直无解。
    我的主要目标是得到 parentWindow 然后可以执行 execScript 即可。
    实在找不到比这更好的方法了。
      

  3.   

    放一段测试代码很好的解释了我现在碰到的问题。
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Diagnostics;
    using System.Reflection;
    using System.Windows.Forms;
    using mshtml;
    using SHDocVw;namespace InternetWebbrowser
    {
        class OpenIE
        {
            public OpenIE()
            {
                this.get_IE_Window();
            }        [STAThread]
            private void get_IE_Window()
            {
                InternetExplorer ie = new InternetExplorerClass();
                object url = "http://www.sina.com.cn";
                object nill = null;
                ie.Visible = true;
                ie.Navigate2(ref url, ref nill, ref nill, ref nill, ref nill);
                ie.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.IE_DocumentComplete);
            }        [STAThread]
            void IE_DocumentComplete(object pDisp, ref object URL)
            {
                Console.WriteLine(System.Threading.Thread.CurrentThread.GetApartmentState().ToString());
                try
                {
                    ((IHTMLDocument2)((SHDocVw.IWebBrowserApp)pDisp).Document).parentWindow.execScript("alert('Hello World!')", "JavaScript");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message + "\n\r" + exp.Source + "\n\r" + exp.StackTrace);
                }
            }
        }
    }
      

  4.   

    可能是我对 [STAThread] 理解的不是很深刻,就在所有的方法上都加上了。原本预计会弹出一个 Hellow World! 对话框的,最后只在 Console 端得到了一个 System.InvalidCastException 错误。有谁可以提示下该如何修复这个错误呢?