I am creating a wpf application where I am using a webbrowser control. anyways sometimes I am required to look for html elements, invoke clicks, and other basic functionality.
In winforms webbrowser control I am able to achieve this by doing:
webBrowser1.Document.GetElementById("someId").SetAttribute("value", "I change the value");
In wpf webbrowser control I managed to achieve the same thing by doing:
dynamic d = webBrowser1.Document;
var el = d.GetElementById("someId").SetAttribute("value", "I change the value");
I also managed to invoke a click in the wpf webbrowser control by using the dynamic type. Sometimes I get exeptions though.
How will I be able to look for html elements, set attributes and invoke clicks in a wpf webbrowser control without having to use dynamic types where I often get exceptions? I will like to replace my winforms webbrowser control in my wpf application by a wpf webbrowser control.
Use the following namespace that way you can get to all element properties and eventhandler properties:
using mshtml;
private mshtml.HTMLDocumentEvents2_Event documentEvents;
private mshtml.IHTMLDocument2 documentText;
in constructor or xaml set your LoadComplete event:
webBrowser.LoadCompleted += webBrowser_LoadCompleted;
then in that method create your new webbrowser document object and view the available properties and create new events as follows:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With