WPF webbrowser控件与winforms
我正在使用webbrowser控件创建一个wpf应用程序。无论如何,有时我需要查找html元素、调用单击和其他基本功能 在winforms webbrowser控件中,我可以通过执行以下操作来实现这一点:WPF webbrowser控件与winforms,wpf,winforms,automation,webbrowser-control,Wpf,Winforms,Automation,Webbrowser Control,我正在使用webbrowser控件创建一个wpf应用程序。无论如何,有时我需要查找html元素、调用单击和其他基本功能 在winforms webbrowser控件中,我可以通过执行以下操作来实现这一点: webBrowser1.Document.GetElementById("someId").SetAttribute("value", "I change the value"); dynamic d = webBrowser1.Document; var el = d.Get
webBrowser1.Document.GetElementById("someId").SetAttribute("value", "I change the value");
dynamic d = webBrowser1.Document;
var el = d.GetElementById("someId").SetAttribute("value", "I change the value");
在wpf webbrowser控件中,我通过以下操作实现了相同的目标:
webBrowser1.Document.GetElementById("someId").SetAttribute("value", "I change the value");
dynamic d = webBrowser1.Document;
var el = d.GetElementById("someId").SetAttribute("value", "I change the value");
我还通过使用动态类型在wpf webbrowser控件中调用了单击。不过有时候我会得到豁免
如何才能在wpf webbrowser控件中查找html元素、设置属性和调用单击操作,而不必使用经常出现异常的动态类型?我想用wpf webbrowser控件替换wpf应用程序中的winforms webbrowser控件 我这样做的方式是 下载要使用HTTPRequest呈现的页面的HTML文本。在HTML文本中使用HTML agility pack注入java脚本。如果您想使用jQuery,那么必须首先对页面进行jQuery,然后将事件与dom元素绑定。您还可以从脚本中调用c#函数,或者以其他方式调用。 没有与动态类型混淆,因此也没有例外 您还可以在WC上使用扩展方法抑制脚本错误
并且可能会有所帮助。使用以下名称空间,这样您就可以访问所有元素属性和eventhandler属性:
using mshtml;
private mshtml.HTMLDocumentEvents2_Event documentEvents;
private mshtml.IHTMLDocument2 documentText;
在构造函数或xaml中设置LoadComplete事件:
webBrowser.LoadCompleted += webBrowser_LoadCompleted;
然后在该方法中创建新的webbrowser文档对象,查看可用属性并创建新事件,如下所示:
private void webBrowser_LoadCompleted(object sender, NavigationEventArgs e)
{
documentText = (IHTMLDocument2)webBrowserChat.Document; //this will access the document properties as needed
documentEvents = (HTMLDocumentEvents2_Event)webBrowserChat.Document; // this will access the events properties as needed
documentEvents.onkeydown += webBrowserChat_MouseDown;
documentEvents.oncontextmenu += webBrowserChat_ContextMenuOpening;
}
private void webBrowser_MouseDown(IHTMLEventObj pEvtObj)
{
pEvtObj.returnValue = false; // Stops key down
pEvtObj.returnValue = true; // Return value as pressed to be true;
}
private bool webBrowserChat_ContextMenuOpening(IHTMLEventObj pEvtObj)
{
return false; // ContextMenu wont open
// return true; ContextMenu will open
// Here you can create your custom contextmenu or whatever you want
}
Winforms HtmlDocument和HtmlElement包装器类很好。但是,当DOM不包含您希望它包含的元素或属性时,它会发出同样响亮的声音。它们也要求显式检查null以避免爆炸。我确信文档包含我正在寻找的html元素,因为我创建html文档是为了测试目的。但我同意我会一直检查空例外。。。