How to: Access the Managed HTML Document Object Model

You can access the managed HTML Document Object Model (DOM) from two types of applications:

  • A Windows Forms application (.exe) that hosted the managed WebBrowser control. These two technologies complement one another, with the WebBrowser control displaying the page to the user and the HTML DOM representing the document's logical structure.

  • A Windows Forms UserControl hosted within Internet Explorer. You can access the HTML DOM representing the page on which your UserControl is hosted in order to change the document's structure or open modal dialog boxes, among many other possibilities.

To access DOM from a Windows Forms application

  1. Host a WebBrowser control within your Windows Forms application and monitor for the DocumentCompleted event. For details on hosting controls and monitoring for events, see Events.

  2. Retrieve the HtmlDocument for the current page by accessing the Document property of the WebBrowser control.

To access DOM from a UserControl hosted in Internet Explorer

  1. Create your own custom derived class of the UserControl class. For more information, see How to: Author Composite Controls.

  2. Place the following code inside of your Load event handler for your UserControl:

HtmlDocument doc = null;

private void UserControl1_Load(object sender, EventArgs e)
{
    if (this.Site != null)
    {
        doc = (HtmlDocument)this.Site.GetService(typeof(HtmlDocument));
    }
}
Private Sub UserControl1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If (Me.Site IsNot Nothing) Then
        Dim Doc As HtmlDocument = CType(Me.Site.GetService(Type.GetType("System.Windows.Forms.HtmlDocument")), HtmlDocument)
    End If
End Sub

Robust Programming

  1. When using the DOM through the WebBrowser control, you should always wait until the DocumentCompleted event occurs before attempting to access the Document property of the WebBrowser control. The DocumentCompleted event is raised after the entire document has loaded; if you use the DOM before then, you risk causing a run-time exception in your application.

.NET Framework Security

  1. Your application or UserControl will require full trust in order to access the managed HTML DOM. If you are deploying a Windows Forms application using ClickOnce, you can request full trust using either Permission Elevation or Trusted Application Deployment; see Securing ClickOnce Applications for details.

See also