HtmlDocument 类


提供对 WebBrowser 控件承载的 HTML 文档的顶级编程访问。Provides top-level programmatic access to an HTML document hosted by the WebBrowser control.

public ref class HtmlDocument sealed
public sealed class HtmlDocument
type HtmlDocument = class
Public NotInheritable Class HtmlDocument


下面的代码示例使用 Northwind 数据库中的数据 HTML TABLE 通过动态创建 CreateElementThe following code example uses data from the Northwind database to create an HTML TABLE dynamically using CreateElement. AppendChild此外,还使用方法将单元 (TD 元素添加) 到行 (TR 元素) ,然后将行添加到表中,最后将表追加到当前文档的末尾。The AppendChild method is also used, first to add cells (TD elements) to rows (TR elements), then to add rows to the table, and finally to append the table to the end of the current document. 此代码示例要求你的应用程序具有一个 WebBrowser 名为的控件 WebBrowser1The code example requires that your application has a WebBrowser control named WebBrowser1. 加载文档后应调用该代码。The code should be called after a document has been loaded.

private void DisplayCustomersTable()
    DataSet customersSet = new DataSet();
    DataTable customersTable = null;
    SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Customers", "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;");
    customersTable = customersSet.Tables[0];

    if (webBrowser1.Document != null)
        HtmlElement tableRow = null;
        HtmlElement headerElem = null;

        HtmlDocument doc = webBrowser1.Document;
        HtmlElement tableElem = doc.CreateElement("TABLE");

        HtmlElement tableHeader = doc.CreateElement("THEAD");
        tableRow = doc.CreateElement("TR");

        foreach (DataColumn col in customersTable.Columns)
            headerElem = doc.CreateElement("TH");
            headerElem.InnerText = col.ColumnName;

        // Create table rows.
        HtmlElement tableBody = doc.CreateElement("TBODY");
        foreach (DataRow dr in customersTable.Rows)
            tableRow = doc.CreateElement("TR");
            foreach (DataColumn col in customersTable.Columns)
                Object dbCell = dr[col];
                HtmlElement tableCell = doc.CreateElement("TD");
                if (!(dbCell is DBNull))
                    tableCell.InnerText = dbCell.ToString();
Private Sub DisplayCustomersTable()
    ' Initialize the database connection.
    Dim CustomerData As New DataSet()
    Dim CustomerTable As DataTable

        Dim DBConn As New SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")
        Dim DBQuery As New SqlDataAdapter("SELECT * FROM CUSTOMERS", DBConn)
    Catch dbEX As DataException

    End Try

    CustomerTable = CustomerData.Tables("Customers")

    If (Not (WebBrowser1.Document Is Nothing)) Then
        With WebBrowser1.Document
            Dim TableElem As HtmlElement = .CreateElement("TABLE")

            Dim TableRow As HtmlElement

            ' Create the table header. 
            Dim TableHeader As HtmlElement = .CreateElement("THEAD")
            TableRow = .CreateElement("TR")

            Dim HeaderElem As HtmlElement
            For Each Col As DataColumn In CustomerTable.Columns
                HeaderElem = .CreateElement("TH")
                HeaderElem.InnerText = Col.ColumnName

            ' Create table rows.
            Dim TableBody As HtmlElement = .CreateElement("TBODY")
            For Each Row As DataRow In CustomerTable.Rows
                TableRow = .CreateElement("TR")
                For Each Col As DataColumn In CustomerTable.Columns
                    Dim Item As Object = Row(Col)
                    Dim TableCell As HtmlElement = .CreateElement("TD")
                    If Not (TypeOf (Item) Is DBNull) Then
                        TableCell.InnerText = CStr(Item)
                    End If

        End With
    End If
End Sub


HtmlDocument 提供围绕 Internet Explorer 文档对象(也称为 HTML 文档对象模型 (DOM) )的托管包装。HtmlDocument provides a managed wrapper around Internet Explorer's document object, also known as the HTML Document Object Model (DOM). 您可以 HtmlDocument 通过控件的属性获取的实例 Document WebBrowserYou obtain an instance of HtmlDocument through the Document property of the WebBrowser control.

HTML 文档中的 HTML 标记可以相互嵌套。HTML tags inside of an HTML document can be nested inside one another. HtmlDocument 因此表示文档树,其子级是类的实例 HtmlElementHtmlDocument thus represents a document tree, whose children are instances of the HtmlElement class. 下面的代码示例演示一个简单的 HTML 文件。The following code example shows a simple HTML file.

        <DIV name="Span1">Simple HTML Form</DIV>  
            <SPAN name="TextLabel">Enter Your Name:</SPAN>  
            <INPUT type="text" size="20" name="Text1">  

在此示例中, HtmlDocument 表示标记中的整个文档 HTMLIn this example, HtmlDocument represents the entire document inside the HTML tags. BODYDIV FORM 和标记由 SPAN 单个 HtmlElement 对象表示。The BODY, DIV, FORM and SPAN tags are represented by individual HtmlElement objects.

可以通过多种方式访问此树中的元素。There are several ways you can access the elements in this tree. 使用 Body 属性可以访问 BODY 标记及其所有子级。Use the Body property to access the BODY tag and all of its children. ActiveElement属性为您提供了 HtmlElement HTML 页面上具有用户输入焦点的元素的。The ActiveElement property gives you the HtmlElement for the element on an HTML page that has user input focus. HTML 页面中的所有元素都可以具有名称; All 集合 HtmlElement 使用其名称作为索引来提供对每个的访问。All elements within an HTML page can have a name; the All collection provides access to each HtmlElement using its name as an index. GetElementsByTagName 将返回 HtmlElementCollection HtmlElement 具有给定 HTML 标记名称的所有对象的,如 DIVTABLEGetElementsByTagName will return an HtmlElementCollection of all HtmlElement objects with a given HTML tag name, such as DIV or TABLE. GetElementById 将返回 HtmlElement 对应于你提供的唯一 ID 的单个。GetElementById will return the single HtmlElement corresponding to the unique ID that you supply. GetElementFromPoint 将返回 HtmlElement 可在屏幕上提供的鼠标指针坐标处找到的。GetElementFromPoint will return the HtmlElement that can be found on the screen at the supplied mouse pointer coordinates.

你还可以使用 FormsImages 集合分别循环访问表示用户输入窗体和图形的元素。You can also use the Forms and Images collection to iterate through elements that represent user input forms and graphics, respectively.

HtmlDocument 基于 Internet Explorer 的 DHTML DOM 实现的非托管接口: IHTMLDocumentIHTMLDocument2IHTMLDocument3IHTMLDocument4HtmlDocument is based on the unmanaged interfaces implemented by Internet Explorer's DHTML DOM: IHTMLDocument, IHTMLDocument2, IHTMLDocument3, and IHTMLDocument4. 只公开了这些非托管接口上最常用的属性和方法 HtmlDocumentOnly the most frequently used properties and methods on these unmanaged interfaces are exposed by HtmlDocument. 您可以使用属性直接访问所有其他属性和方法 DomDocument ,您可以将其强制转换为所需的非托管接口指针。You can access all other properties and methods directly using the DomDocument property, which you can cast to the desired unmanaged interface pointer.

HTML 文档可以包含框架,这些框架是控件内部的不同窗口 WebBrowserAn HTML document may contain frames, which are different windows inside of the WebBrowser control. 每个帧都显示其自己的 HTML 页面。Each frame displays its own HTML page. Frames集合可通过 Window 属性获得。The Frames collection is available through the Window property. 你还可以使用 Window 属性来调整所显示页面的大小,滚动文档,或向用户显示警报和提示。You may also use the Window property to resize the displayed page, scroll the document, or display alerts and prompts to the user.

HtmlDocument 公开托管 HTML 页面时应处理的最常见事件。HtmlDocument exposes the most common events you would expect to handle when hosting HTML pages. 对于不是由接口直接公开的事件,可以使用为事件添加处理程序 AttachEventHandlerFor events not exposed directly by the interface, you can add a handler for the event using AttachEventHandler.

HTML 文件可能包含 SCRIPT 标记,这些标记封装用一种活动脚本语言(如 JScript 或 VBScript)编写的代码。HTML files may contain SCRIPT tags that encapsulate code written in one of the Active Scripting languages, such as JScript or VBScript. InvokeScript方法提供了在标记中定义的属性和方法的执行 SCRIPTThe InvokeScript method provides for execution of properties and methods defined in a SCRIPT tag.


虽然上的大多数属性、方法和事件与非托管 DOM 上的属性、方法和事件的名称相同,但某些属性、方法和事件已 HtmlDocument 更改,以便与 .NET Framework 保持一致。While most of the properties, methods, and events on HtmlDocument have kept the same names as they have on the unmanaged DOM, some have been changed for consistency with the .NET Framework.



提供当前具有用户输入焦点的 HtmlElementProvides the HtmlElement which currently has user input focus.


获取或设置超链接被用户单击后的 ColorGets or sets the Color of a hyperlink when clicked by a user.


获取 HtmlElementCollection 的实例,该实例存储文档的所有 HtmlElement 对象。Gets an instance of HtmlElementCollection, which stores all HtmlElement objects for the document.


获取或设置 HTML 文档的背景色。Gets or sets the background color of the HTML document.


获取 BODY 标记的 HtmlElementGets the HtmlElement for the BODY tag.


获取或设置与此文档关联的 HTTP Cookie。Gets or sets the HTTP cookies associated with this document.


获取默认情况下为当前文档使用的编码。Gets the encoding used by default for the current document.


获取或设置字符串,描述用于安全目的的此文档的域。Gets or sets the string describing the domain of this document for security purposes.


获取此 HtmlDocument 的非托管接口指针。Gets the unmanaged interface pointer for this HtmlDocument.


获取或设置此文档的字符编码。Gets or sets the character encoding for this document.


获取一个值,该值指示文档是否具有用户输入焦点。Gets a value indicating whether the document has user input focus.


获取或设置文档的文本颜色。Gets or sets the text color for the document.


获取文档中所有 < 窗体 > 元素的集合。Gets a collection of all of the <FORM> elements in the document.


获取文档中所有图像标记的集合。Gets a collection of all image tags in the document.


获取或设置超链接的颜色。Gets or sets the color of hyperlinks.


获取此 HTML 文档中所有超链接的列表。Gets a list of all the hyperlinks within this HTML document.


获取或设置当前文档中文本的方向。Gets or sets the direction of text in the current document.


获取或设置当前 HTML 文档中 < 标题 > 标记的文本值。Gets or sets the text value of the <TITLE> tag in the current HTML document.


获取描述此文档位置的 URL。Gets the URL describing the location of this document.


获取或设置用户已经访问的链接(指向 HTML 页)的颜色。Gets or sets the Color of links to HTML pages that the user has already visited.


获取与此文档关联的 HtmlWindowGets the HtmlWindow associated with this document.


AttachEventHandler(String, EventHandler)

为已命名的 HTML DOM 事件添加事件处理程序。Adds an event handler for the named HTML DOM event.


新建一个指定 HTML 标记类型的 HtmlElementCreates a new HtmlElement of the specified HTML tag type.

DetachEventHandler(String, EventHandler)

从 HTML DOM 上的命名事件中移除事件处理程序。Removes an event handler from a named event on the HTML DOM.


测试对象是否与当前对象相等。Tests the object for equality against the current object.

ExecCommand(String, Boolean, Object)

对文档执行指定的命令。Executes the specified command against the document.


在当前文档上设置用户输入焦点。Sets user input focus on the current document.


将元素的 ID 特性用作搜索键来检索单个 HtmlElementRetrieves a single HtmlElement using the element's ID attribute as a search key.


检索位于指定工作区坐标位置的 HTML 元素。Retrieves the HTML element located at the specified client coordinates.


检索具有指定 HTML 标记的元素集合。Retrieve a collection of elements with the specified HTML tag.


检索此对象的哈希代码。Retrieves the hash code for this object.


获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)

执行在 HTML 页面中定义的活动脚本函数。Executes an Active Scripting function defined in an HTML page.

InvokeScript(String, Object[])

执行在 HTML 页面中定义的活动脚本函数。Executes an Active Scripting function defined in an HTML page.


创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)

获取一个新的 HtmlDocument,以便与 Write(String) 方法一起使用。Gets a new HtmlDocument to use with the Write(String) method.


返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

编写一个新的 HTML 页。Writes a new HTML page.


Equality(HtmlDocument, HtmlDocument)

返回一个值,该值指示指定的 HtmlDocument 实例是否表示同一个值。Returns a value that indicates whether the specified HtmlDocument instances represent the same value.

Inequality(HtmlDocument, HtmlDocument)

返回一个值,该值指示指定的 HtmlDocument 实例是否不表示同一个值。Returns a value that indicates whether the specified HtmlDocument instances do not represent the same value.



当用户单击文档上的任何位置时发生。Occurs when the user clicks anywhere on the document.


当用户请求显示文档的上下文菜单时发生。Occurs when the user requests to display the document's context menu.


在将焦点提供给文档之前发生。Occurs before focus is given to the document.


在焦点离开控件时发生。Occurs while focus is leaving a control.


当用户单击鼠标左键时发生。Occurs when the user clicks the left mouse button.


当鼠标不再悬停于文档上时发生。Occurs when the mouse is no longer hovering over the document.


当鼠标移到文档上时发生。Occurs when the mouse is moved over the document.


当鼠标移到文档上时发生。Occurs when the mouse is moved over the document.


当用户释放鼠标左键时发生。Occurs when the user releases the left mouse button.


当向其他网页的导航被中断时发生。Occurs when navigation to another Web page is halted.