C#:如何从WebBrowser元素获取文档标题?

Ran*_*ary 5 c# browser document title

我在尝试从C#中的WebBrowser获取文档标题时遇到问题.它在VB.NET中运行良好,但它不会给我任何C#属性.

当我输入MyBrowser.Document时.,我得到的唯一选项是4种方法:Equals,GetHashCode,GetType和ToString - 没有属性.

我认为这是因为我必须首先将文档分配给新实例,但我找不到VB.NET中存在的HTMLDocument类.

基本上我想要做的是每次WebBrowser加载/重新加载页面时返回Document.Title.

有人可以帮忙吗?非常感谢!

这是我目前的代码......

private void Link_Click(object sender, RoutedEventArgs e)
{
    WebBrowser tempBrowser = new WebBrowser();
    tempBrowser.HorizontalAlignment = HorizontalAlignment.Left;
    tempBrowser.Margin = new Thickness(-4, -4, -4, -4);
    tempBrowser.Name = "MyBrowser";
    tempBrowser.VerticalAlignment = VerticalAlignment.Top;
    tempBrowser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(tempBrowser_LoadCompleted);

    tempTab.Content = tempBrowser; // this is just a TabControl that contains the WebBrowser

    Uri tempURI = new Uri("http://www.google.com");
    tempBrowser.Navigate(tempURI);
}

private void tempBrowser_LoadCompleted(object sender, EventArgs e)
{
    if (sender is WebBrowser)
    {
        MessageBox.Show("Test");
        currentBrowser = (WebBrowser)sender;
        System.Windows.Forms.HtmlDocument tempDoc = (System.Windows.Forms.HtmlDocument)currentBrowser.Document;
        MessageBox.Show(tempDoc.Title);
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码没有给我任何错误,但我从来没有看到第二个MessageBox.我确实看到第一个("测试"消息),所以程序进入该代码块.

Han*_*ant 2

您没有使用 Windows 窗体 WebBrowser 控件。我认为您已经获得了 ieframe.dll 的 COM 包装器,它的名称是 AxWebBrowser。通过在“解决方案资源管理器”窗口中打开“引用”节点来验证这一点。如果您看到 AxSHDocVw,那么您的控制有误。它非常不友好,它只是为您提供了 Document 属性的不透明接口指针。您确实只会获得默认的对象类成员。

查看工具箱。选择 WebBrowser 而不是“Microsoft Web 浏览器”。