WebBrowser .NET控件 - 如何检查以前的事件是否已完成?

时间:2014-12-29 15:07:42

标签: c# multithreading web-controls

一开始我想道歉,因为问题标题可能会产生误导,但我找不到更好的方法来命名。

问题在于:

我有从文件中读取帐户信息的应用程序,然后基于此,假设登录到网站 - 当通过WebBrowser的DocumentComplete事件执行每个步骤时,一切都很好,但我想重写代码使它看起来更好,更容易修改和升级。

现在,为了登录,我必须从网站获取令牌,然后使用登录名,密码和令牌发送postdata,所以我想创建两种方法:

A)为gettoken b)中的LogIn

现在他们看起来像:(尝试用户给出了解决方案,但仍然没有工作)

       public void GetToken()
                {
                    browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(AfterLoadingTokenSite);
                    browser.Navigate("https://somewebsite.com");
                }

    private void AfterLoadingTokenSite(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                //here code which parse HTML in order to find token - works perfectly

            }

            public void LogIn()
            {
                string postData = string.Format("_mToken={0}&userID={1}&userPW={2}", userToken, userID, userPW);
                UTF8Encoding standardEncoding = new UTF8Encoding();

                browser.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(AfterLoadingTokenSite);
                browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(AfterLoadingLoginSite);

                browser.Navigate("https://www.somewebsite.com/login/", "", standardEncoding.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");
            }

            private void AfterLoadingLoginSite(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
                    return; 
                else if (browser.DocumentText.Contains("Logged in as"))
                {
                    _logged = true;
                }
            }


And on FormLoad event I wanted to load all accounts from file to List and then do something like that:

    LoadAccountsFromFile();
    if (loadedAccounts)
    {
         foreach (Account n in AllAccounts)
         {
              n.GetToken();
              n.LogIn();
         }
    }

但是这并不起作用,因为据我所知,没有默认机制让WebControl在启动下一个事件之前等待上一个事件完成,所以我的代码直接进入LogIn而不等待AfterLoadingTokenSite()完成

所以我的问题是如何阻止它?

必须在.NET 3.5中完成。

0 个答案:

没有答案