HtmlDocument HtmlDocument HtmlDocument HtmlDocument Class


提供对 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属性的WebBrowser控件。You 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 因此表示其子级是实例的文档树的HtmlElement类。HtmlDocument 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表示整个文档内的HTML标记。In this example, HtmlDocument represents the entire document inside the HTML tags. BODYDIVFORMSPAN标记由个人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 实现的非托管接口: IHTMLDocumentIHTMLDocument2IHTMLDocument3,和IHTMLDocument4HtmlDocument 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 文档可能包含不同的窗口的帧内的WebBrowser控件。An 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方法用于执行属性和方法中定义SCRIPT标记。The InvokeScript method provides for execution of properties and methods defined in a SCRIPT tag.


尽管大多数属性、 方法和事件上HtmlDocument具有保留相同的名称,因为它们对非托管的 DOM 与某些已更改为与一致.NET Framework.NET FrameworkWhile 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.NET Framework.


ActiveElement ActiveElement ActiveElement ActiveElement

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

ActiveLinkColor ActiveLinkColor ActiveLinkColor ActiveLinkColor

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

All All All All

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

BackColor BackColor BackColor BackColor

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

Body Body Body Body

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

Cookie Cookie Cookie Cookie

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

DefaultEncoding DefaultEncoding DefaultEncoding DefaultEncoding

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

Domain Domain Domain Domain

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

DomDocument DomDocument DomDocument DomDocument

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

Encoding Encoding Encoding Encoding

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

Focused Focused Focused Focused

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

ForeColor ForeColor ForeColor ForeColor

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

Forms Forms Forms Forms

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

Images Images Images Images

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

LinkColor LinkColor LinkColor LinkColor

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

Links Links Links Links

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

RightToLeft RightToLeft RightToLeft RightToLeft

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

Title Title Title Title

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

Url Url Url Url

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

VisitedLinkColor VisitedLinkColor VisitedLinkColor VisitedLinkColor

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

Window Window Window Window

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


AttachEventHandler(String, EventHandler) AttachEventHandler(String, EventHandler) AttachEventHandler(String, EventHandler) AttachEventHandler(String, EventHandler)

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

CreateElement(String) CreateElement(String) CreateElement(String) CreateElement(String)

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

DetachEventHandler(String, EventHandler) DetachEventHandler(String, EventHandler) DetachEventHandler(String, EventHandler) DetachEventHandler(String, EventHandler)

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

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

ExecCommand(String, Boolean, Object) ExecCommand(String, Boolean, Object) ExecCommand(String, Boolean, Object) ExecCommand(String, Boolean, Object)

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

Focus() Focus() Focus() Focus()

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

GetElementById(String) GetElementById(String) GetElementById(String) GetElementById(String)

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

GetElementFromPoint(Point) GetElementFromPoint(Point) GetElementFromPoint(Point) GetElementFromPoint(Point)

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

GetElementsByTagName(String) GetElementsByTagName(String) GetElementsByTagName(String) GetElementsByTagName(String)

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

GetType() GetType() GetType() GetType()

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

(Inherited from Object)
InvokeScript(String) InvokeScript(String) InvokeScript(String) InvokeScript(String)

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

InvokeScript(String, Object[]) InvokeScript(String, Object[]) InvokeScript(String, Object[]) InvokeScript(String, Object[])

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

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
OpenNew(Boolean) OpenNew(Boolean) OpenNew(Boolean) OpenNew(Boolean)

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

ToString() ToString() ToString() ToString()

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

(Inherited from Object)
Write(String) Write(String) Write(String) Write(String)

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


Click Click Click Click

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

ContextMenuShowing ContextMenuShowing ContextMenuShowing ContextMenuShowing

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

Focusing Focusing Focusing Focusing

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

LosingFocus LosingFocus LosingFocus LosingFocus

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

MouseDown MouseDown MouseDown MouseDown

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

MouseLeave MouseLeave MouseLeave MouseLeave

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

MouseMove MouseMove MouseMove MouseMove

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

MouseOver MouseOver MouseOver MouseOver

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

MouseUp MouseUp MouseUp MouseUp

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

Stop Stop Stop Stop

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


Equality(HtmlDocument, HtmlDocument) Equality(HtmlDocument, HtmlDocument) Equality(HtmlDocument, HtmlDocument) Equality(HtmlDocument, HtmlDocument)

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

Inequality(HtmlDocument, HtmlDocument) Inequality(HtmlDocument, HtmlDocument) Inequality(HtmlDocument, HtmlDocument) Inequality(HtmlDocument, HtmlDocument)

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