【问题标题】:Navigating to a url using a winforms webbrowser in a wpf application在 wpf 应用程序中使用 winforms 网络浏览器导航到 url
【发布时间】:2015-07-22 11:44:09
【问题描述】:

我正在构建一个包含 WebBrowser 的 WPF 应用程序。我想在 webbrowser 中使用Document.GetElementByID 方法,我的理解是在 WPF 中执行此操作的最简单方法是使用 winforms webbrowser 和 WindowsFormsIntegration(如果有更好的方法请告诉我)

我在导航到 URL 时遇到问题。在调试模式下运行程序不会引发任何错误,并且跳过导航代码仍然会使我的网络浏览器具有以下属性:

wb1.ReadyState = Uninitialized
wb1.Url = null

我是否错过了导航到 url 的内容?我可以在 WPF 网络浏览器中使用 Document.GetElementById 方法吗?

xaml:

<Window x:Class="my program's main window"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
...
<WindowsFormsHost Name="wfh">
    <WindowsFormsHost.Child>
        <wf:WebBrowser/>
    </WindowsFormsHost.Child>
</WindowsFormsHost>

代码:

var wb1 = wfh.Child as System.Windows.Forms.WebBrowser;
wb1.Navigate("my url here");
while (wb1.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
{
    // this loop never ends because neither readystate nor wb1.Url ever change
}

【问题讨论】:

    标签: c# .net wpf winforms .net-4.0


    【解决方案1】:

    向您的项目添加对Microsoft.mshtml(来自Assembies > Extensions)的引用。然后使用 WPF WebBrowser 控件并将其Document 属性转换为HTMLDocument

    <WebBrowser x:Name="webBrowser" Navigated="WebBrowserNavigated" />
    

    后面的代码:

    using mshtml;
    ...
    
    webBrowser.Navigate("...");
    ...
    
    private void WebBrowserNavigated(object sender, NavigationEventArgs e)
    {
        var document = webBrowser.Document as HTMLDocument;
        ...
    }
    

    【讨论】:

    • 谢谢,很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 2014-03-23
    • 2011-10-26
    相关资源
    最近更新 更多