我需要从网页获取一些信息并在 MainWindow 上显示相同的信息。我正在调用一个编写在一个单独的库中的例程,一旦加载了网页,它的属性就会提供这些信息。
我在stackoverflow上看了很多,找到了各种解决方案;但没有一个对我有用。这是我的例程:
protected System.Windows.Forms.WebBrowser wb;
public void ObtainProfileInformation()
{
url = CUSTOMER_PROFILE_URL;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url));
try
{
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
var th = new System.Threading.Thread(() =>
{
wb = new System.Windows.Forms.WebBrowser() { Visible = false, ScriptErrorsSuppressed = true };
wb.DocumentCompleted += (sender, e) =>
{
string target_url = wb.Url.AbsoluteUri;
if ((target_url.Contains("login") == false))
{
var html_text = wb.DocumentText;
HtmlAgilityPack.HtmlDocument html_document = new HtmlAgilityPack.HtmlDocument();
html_document.LoadHtml(html_text);
foreach (var MatchingDiv in html_document.DocumentNode.Descendants("span"))
{
if (MatchingDiv.Id.Contains("lblFullName"))
{
CustomerName = MatchingDiv.InnerText;
}
if (MatchingDiv.Id.Contains("lblCompany"))
{
CompanyName = MatchingDiv.InnerText;
}
if (MatchingDiv.Id.Contains("lblTitle"))
{
CustomerTitle = MatchingDiv.InnerText;
}
if (MatchingDiv.Id.Contains("lblEmail"))
{
CustomerEmail = MatchingDiv.InnerText.Split(new char[] { ':' })[1].TrimStart();
}
if (MatchingDiv.Id.Contains("lblUsername"))
{
CustomerUserName = MatchingDiv.InnerText.Split(new char[] { ':' })[1].TrimStart();
}
}
}
System.Windows.Forms.Application.ExitThread();
};
wb.Navigate(url);
System.Windows.Forms.Application.Run();
});
th.SetApartmentState(System.Threading.ApartmentState.STA);
th.Start();
}
catch (WebException)
{
wb.Dispose();
}
catch (Exception ex)
{
wb.Dispose();
throw new Exception("Something strange", ex);
}
}
DocumentCompleted 事件被触发并且属性 CustomerName 等被填充但是在窗口的加载事件完成之后。所以我无法在窗口上更改它们。