- Общие сведения об элементе управления WebBrowser (Windows Forms) WebBrowser Control (Windows Forms)
- в этом разделе In This Section
- Справочник Reference
- Web Browser. Document Property
- Definition
- Property Value
- Exceptions
- Examples
- Remarks
- Web Browser. Document Text Property
- Definition
- Property Value
- Exceptions
- Examples
- Remarks
- Web Browser. Document Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Web Browser. Document Text Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
Общие сведения об элементе управления WebBrowser (Windows Forms) WebBrowser Control (Windows Forms)
WebBrowser Элемент управления Windows Forms размещает веб-страницы и предоставляет возможности для обзора в приложении. The Windows Forms WebBrowser control hosts webpages and provides web browsing capabilities to your application.
в этом разделе In This Section
Общие сведения об элементе управления WebBrowser WebBrowser Control Overview
Описание элемента управления, его основных возможностей и свойств. Explains what this control is and its key features and properties.
Безопасность элемента управления WebBrowser WebBrowser Security
Описание проблем безопасности, связанных с элементом управления. Explains security issues related to the control.
Практическое руководство. Переход по заданному URL с помощью элемента управления WebBrowser How to: Navigate to a URL with the WebBrowser Control
Демонстрирует использование элемента управления для перехода по определенному URL-адресу. Demonstrates how to use the control to navigate to a specific URL.
Практическое руководство. Печать с использованием элемента управления WebBrowser How to: Print with a WebBrowser Control
Демонстрирует печать веб-страницы без ее отображения. Demonstrates how to print a Web page without displaying it.
Практическое руководство. Добавление функциональности веб-браузера в приложения Windows Forms How to: Add Web Browser Capabilities to a Windows Forms Application
Описание инициализации элемента управления для использования в качестве веб-браузера. Describes how to initialize the control for use as a Web browser.
Практическое руководство. Создание средства просмотра HTML-документов в приложении Windows Forms How to: Create an HTML Document Viewer in a Windows Forms Application
Описание инициализации элемента управления для использования в качестве средства просмотра HTML-страниц. Describes how to initialize the control for use as an HTML viewer.
Практическое руководство. Реализация двунаправленного взаимодействия между кодом DHTML и клиентским кодом приложений How to: Implement Two-Way Communication Between DHTML Code and Client Application Code
Описывает, как настроить двустороннюю связь между кодом приложения и DHTML на веб-странице, размещенной в элементе управления. Describes how to set up two-way communication between your application code and DHTML in a Web page hosted by the control.
Использование управляемой объектной модели HTML-документов Using the Managed HTML Document Object Model
Содержит разделы, описывающие способ управления или создания HTML-страниц, размещенных в WebBrowser элементе управления. Provides topics that describe how to manipulate or create HTML pages hosted by the WebBrowser control.
Справочник Reference
Класс WebBrowser WebBrowser class
Описание класса и всех его членов. Describes this class and has links to all its members.
WebBrowserDocumentCompletedEventArgs
Описание класса и всех его членов. Describes this class and has links to all its members.
WebBrowserEncryptionLevel
Описывает это перечисление и все его значения. Describes this enumeration and all its values.
WebBrowserNavigatedEventArgs
Описание класса и всех его членов. Describes this class and has links to all its members.
WebBrowserNavigatedEventHandler
Описывает этот делегат. Describes this delegate.
WebBrowserNavigatingEventArgs
Описание класса и всех его членов. Describes this class and has links to all its members.
WebBrowserNavigatingEventHandler
Описывает этот делегат. Describes this delegate.
WebBrowserProgressChangedEventArgs
Описание класса и всех его членов. Describes this class and has links to all its members.
WebBrowserProgressChangedEventHandler
Описывает этот делегат. Describes this delegate.
WebBrowserReadyState
Описывает это перечисление и все его значения. Describes this enumeration and all its values.
WebBrowserRefreshOption
Описывает это перечисление и все его значения. Describes this enumeration and all its values.
Web Browser. Document Property
Definition
Gets an HtmlDocument representing the Web page currently displayed in the WebBrowser control.
Property Value
An HtmlDocument representing the current page, or null if no page is loaded.
Exceptions
This WebBrowser instance is no longer valid.
A reference to an implementation of the IWebBrowser2 interface could not be retrieved from the underlying ActiveX WebBrowser control.
Examples
The following code example demonstrates how to use the Document property in a handler for the Navigating event to determine whether a Web page form has been filled in. If the input field does not contain a value, the navigation is canceled.
This example requires that your form contains a WebBrowser control called webBrowser1 .
Remarks
Use this property when you want to access the contents of a Web page displayed in the WebBrowser control through the HTML document object model (DOM). This is useful, for example, when you want to use Web-based controls in your Windows Forms application.
You can use this property, in combination with the ObjectForScripting property, to implement two-way communication between a Web page displayed in the WebBrowser control and your application. Use the HtmlDocument.InvokeScript method to call script methods implemented in a Web page from your client application code. Your scripting code can access your application through the window.external object, which is a built-in DOM object provided for host access, and which maps to an object that you specify for the ObjectForScripting property.
To access the contents of a Web page as a string, use the DocumentText property. To access the contents of a Web page as a Stream, use the DocumentStream property.
Web Browser. Document Text Property
Definition
Gets or sets the HTML contents of the page displayed in the WebBrowser control.
Property Value
The HTML text of the displayed page, or the empty string («») if no document is loaded.
Exceptions
This WebBrowser instance is no longer valid.
A reference to an implementation of the IWebBrowser2 interface could not be retrieved from the underlying ActiveX WebBrowser control.
Examples
The following code example demonstrates how to use the DocumentText property to programmatically display document content of your choosing. This example requires that your form contains a WebBrowser control called webBrowser1 .
Remarks
Use this property when you want to manipulate the contents of an HTML page displayed in the WebBrowser control using string processing tools. You can use this property, for example, to load pages from a database or to analyze pages using regular expressions. When you set this property, the WebBrowser control automatically navigates to the about:blank URL before loading the specified text. This means that the Navigating, Navigated, and DocumentCompleted events occur when you set this property, and the value of the Url property is no longer meaningful.
This property contains the text of the current document, even if another document has been requested. If you set the value of this property and then immediately retrieve it again, the value retrieved may be different than the value set if the WebBrowser control has not had time to load the new content. You can retrieve the new value in a DocumentCompleted event handler. Alternatively, you can block the thread until the document is loaded by calling the Thread.Sleep method in a loop until the DocumentText property returns the value that you originally set it to.
To access the contents of a Web page as a Stream, use the DocumentStream property. You can also access the page contents using the HTML document object model (DOM) through the Document property.
Web Browser. Document Свойство
Определение
Получает объект HtmlDocument, представляющий веб-страницу, отображаемую в текущий момент в элементе управления WebBrowser. Gets an HtmlDocument representing the Web page currently displayed in the WebBrowser control.
Значение свойства
Объект HtmlDocument, представляющий текущую страницу, или значение null , если страница не загружается. An HtmlDocument representing the current page, or null if no page is loaded.
Исключения
Данный экземпляр WebBrowser больше не действителен. This WebBrowser instance is no longer valid.
Не удается получить ссылку на реализацию интерфейса IWebBrowser2 из базового элемента управления ActiveX WebBrowser . A reference to an implementation of the IWebBrowser2 interface could not be retrieved from the underlying ActiveX WebBrowser control.
Примеры
В следующем примере кода показано, как использовать Document свойство в обработчике для события, Navigating чтобы определить, заполнена ли форма веб-страницы. The following code example demonstrates how to use the Document property in a handler for the Navigating event to determine whether a Web page form has been filled in. Если поле ввода не содержит значение, переход отменяется. If the input field does not contain a value, the navigation is canceled.
В этом примере требуется, чтобы форма содержала WebBrowser элемент управления с именем webBrowser1 . This example requires that your form contains a WebBrowser control called webBrowser1 .
Комментарии
Это свойство используется, если требуется получить доступ к содержимому веб-страницы, отображаемой в WebBrowser элементе управления, с помощью модели DOM HTML. Use this property when you want to access the contents of a Web page displayed in the WebBrowser control through the HTML document object model (DOM). Это полезно, например, если вы хотите использовать веб-элементы управления в приложении Windows Forms. This is useful, for example, when you want to use Web-based controls in your Windows Forms application.
Это свойство в сочетании со ObjectForScripting свойством можно использовать для реализации двустороннего взаимодействия между веб-страницей, отображаемой в WebBrowser элементе управления и приложением. You can use this property, in combination with the ObjectForScripting property, to implement two-way communication between a Web page displayed in the WebBrowser control and your application. Используйте HtmlDocument.InvokeScript метод для вызова методов скрипта, реализованных на веб-странице, из кода клиентского приложения. Use the HtmlDocument.InvokeScript method to call script methods implemented in a Web page from your client application code. Код скрипта может получать доступ к приложению через window.external объект, который является встроенным объектом DOM, предоставляемым для доступа к узлу и который соответствует объекту, указанному для ObjectForScripting Свойства. Your scripting code can access your application through the window.external object, which is a built-in DOM object provided for host access, and which maps to an object that you specify for the ObjectForScripting property.
Чтобы получить доступ к содержимому веб-страницы в виде строки, используйте DocumentText свойство. To access the contents of a Web page as a string, use the DocumentText property. Чтобы получить доступ к содержимому веб-страницы в виде Stream , используйте DocumentStream свойство. To access the contents of a Web page as a Stream, use the DocumentStream property.
Web Browser. Document Text Свойство
Определение
Получает или задает HTML-содержимое страницы, отображаемой в элементе управления WebBrowser. Gets or sets the HTML contents of the page displayed in the WebBrowser control.
Значение свойства
HTML-текст отображаемой страницы или пустая строка («»), если никакой документ не загружен. The HTML text of the displayed page, or the empty string («») if no document is loaded.
Исключения
Данный экземпляр WebBrowser больше не действителен. This WebBrowser instance is no longer valid.
Не удается получить ссылку на реализацию интерфейса IWebBrowser2 из базового элемента управления ActiveX WebBrowser . A reference to an implementation of the IWebBrowser2 interface could not be retrieved from the underlying ActiveX WebBrowser control.
Примеры
В следующем примере кода показано, как использовать DocumentText свойство для программного отображения содержимого документа по вашему выбору. The following code example demonstrates how to use the DocumentText property to programmatically display document content of your choosing. В этом примере требуется, чтобы форма содержала WebBrowser элемент управления с именем webBrowser1 . This example requires that your form contains a WebBrowser control called webBrowser1 .
Комментарии
Это свойство используется, если требуется управлять содержимым HTML-страницы, отображаемой в WebBrowser элементе управления с помощью средств обработки строк. Use this property when you want to manipulate the contents of an HTML page displayed in the WebBrowser control using string processing tools. Это свойство можно использовать, например, для загрузки страниц из базы данных или для анализа страниц с помощью регулярных выражений. You can use this property, for example, to load pages from a database or to analyze pages using regular expressions. При задании этого свойства WebBrowser элемент управления автоматически переходит к URL-адресу about: Blank перед загрузкой указанного текста. When you set this property, the WebBrowser control automatically navigates to the about:blank URL before loading the specified text. Это означает, что Navigating Navigated события, и DocumentCompleted происходят при задании этого свойства, и значение Url свойства больше не имеет смысла. This means that the Navigating, Navigated, and DocumentCompleted events occur when you set this property, and the value of the Url property is no longer meaningful.
Это свойство содержит текст текущего документа, даже если был запрошен другой документ. This property contains the text of the current document, even if another document has been requested. Если задать значение этого свойства, а затем сразу же получить его снова, то полученное значение может отличаться от значения, установленного в случае, если WebBrowser элементу управления не пришло время загрузить новое содержимое. If you set the value of this property and then immediately retrieve it again, the value retrieved may be different than the value set if the WebBrowser control has not had time to load the new content. Новое значение можно получить в DocumentCompleted обработчике событий. You can retrieve the new value in a DocumentCompleted event handler. Кроме того, поток можно заблокировать до загрузки документа, вызвав Thread.Sleep метод в цикле до тех пор, пока DocumentText свойство не вернет значение, изначально заданное свойству. Alternatively, you can block the thread until the document is loaded by calling the Thread.Sleep method in a loop until the DocumentText property returns the value that you originally set it to.
Чтобы получить доступ к содержимому веб-страницы в виде Stream , используйте DocumentStream свойство. To access the contents of a Web page as a Stream, use the DocumentStream property. Можно также получить доступ к содержимому страницы с помощью модели HTML-документа (DOM) с помощью Document Свойства. You can also access the page contents using the HTML document object model (DOM) through the Document property.