Windows forms web browser

Web Browser. Go Home Метод

Определение

Перемещает элемент управления WebBrowser на домашнюю страницу текущего пользователя. Navigates the WebBrowser control to the home page of the current user.

Исключения

Данный экземпляр 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.

Примеры

В следующем примере кода показано, как использовать GoHome метод для реализации кнопки Home для WebBrowser элемента управления, аналогичного элементу в Internet Explorer. The following code example demonstrates how to use the GoHome method to implement a Home button for the WebBrowser control similar to the one in Internet Explorer. В этом примере требуется, чтобы форма содержала WebBrowser элемент управления webBrowser1 и Button вызывался элемент управления ButtonHome . This example requires that your form contains a WebBrowser control called webBrowser1 and a Button control called ButtonHome .

Комментарии

Этот метод можно использовать для реализации кнопки Home , аналогичной той, которая имеется в Internet Explorer. You can use this method to implement a Home button similar to the one in Internet Explorer. Пользователь может указать домашнюю страницу в диалоговом окне Свойства обозревателя , доступном из панели управления или меню Сервис в Internet Explorer. The user can specify a home page in the Internet Options dialog box, which is available from Control Panel or from the Tools menu in Internet Explorer.

Web Browser. Navigating Событие

Определение

Происходит перед переходом элемента управления WebBrowser в новый документ. Occurs before the WebBrowser control navigates to a new document.

Тип события

Примеры

В следующем примере кода показано, как с помощью обработчика Navigating события отменить навигацию, если форма веб-страницы не заполнена. The following code example demonstrates how to use a handler for the Navigating event to cancel navigation when a Web page form has not been filled in. DocumentСвойство используется для определения того, содержит ли поле ввода значение. The Document property is used to determine whether the form input field contains a value.

В этом примере требуется, чтобы форма содержала WebBrowser элемент управления, webBrowser1 а класс формы стал ComVisibleAttribute доступным для com. This example requires that your form contains a WebBrowser control called webBrowser1 and that your form class has a ComVisibleAttribute making it accessible to COM.

Полный пример кода, в который можно вставить следующий код, см. в разделе как добавить возможности веб-браузера в Windows Forms приложение. For a complete code example that you can paste the following code into, see How to: Add Web Browser Capabilities to a Windows Forms Application.

Комментарии

WebBrowserЭлемент управления переходит к новому документу каждый раз, когда задано одно из следующих свойств или вызывается метод: The WebBrowser control navigates to a new document whenever one of the following properties is set or methods is called:

NavigatingСобытие можно обменять, чтобы отменить навигацию, если не выполнены определенные условия, например когда пользователь не заполнил форму. You can handle the Navigating event to cancel navigation if certain conditions have not been met, for example, when the user has not completely filled out a form. Чтобы отменить навигацию, установите Cancel свойство объекта, WebBrowserNavigatingEventArgs передаваемое обработчику событий, в значение true . To cancel navigation, set the Cancel property of the WebBrowserNavigatingEventArgs object passed to the event handler to true . Этот объект также можно использовать для получения URL-адреса нового документа через WebBrowserNavigatingEventArgs.Url свойство. You can also use this object to retrieve the URL of the new document through the WebBrowserNavigatingEventArgs.Url property. Если новый документ будет отображаться в кадре веб-страницы, можно получить имя рамки через WebBrowserNavigatingEventArgs.TargetFrameName свойство. If the new document will be displayed in a Web page frame, you can retrieve the name of the frame through the WebBrowserNavigatingEventArgs.TargetFrameName property.

Читайте также:  Astra linux разметка диска после установки

Обрабатывает Navigated событие, чтобы получить уведомление, когда WebBrowser элемент управления завершает навигацию и начал загрузку документа в новом расположении. Handle the Navigated event to receive notification when the WebBrowser control finishes navigation and has begun loading the document at the new location. Обрабатывает DocumentCompleted событие, чтобы получить уведомление, когда WebBrowser элемент управления закончит загрузку нового документа. Handle the DocumentCompleted event to receive notification when the WebBrowser control finishes loading the new document.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

WebBrowser Control Overview

The WebBrowser control provides a managed wrapper for the WebBrowser ActiveX control. The managed wrapper lets you display Web pages in your Windows Forms client applications. You can use the WebBrowser control to duplicate Internet Explorer Web browsing functionality in your application or you can disable default Internet Explorer functionality and use the control as a simple HTML document viewer. You can also use the control to add DHTML-based user interface elements to your form and hide the fact that they are hosted in the WebBrowser control. This approach lets you seamlessly combine Web controls with Windows Forms controls in a single application.

Frequently Used Properties, Methods, and Events

The WebBrowser control has several properties, methods, and events that you can use to implement controls found in Internet Explorer. For example, you can use the Navigate method to implement an address bar, and the GoBack , GoForward , Stop , and Refresh methods to implement navigation buttons on a toolbar. You can handle the Navigated event to update the address bar with the value of the Url property and the title bar with the value of the DocumentTitle property.

If you want to generate your own page content within your application, you can set the DocumentText property. If you are familiar with the HTML document object model (DOM), you can also manipulate the contents of the current Web page through the Document property. With this property, you can store and modify documents in memory instead of navigating among files.

Общие сведения об элементе управления 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.

Читайте также:  Ttl для windows phone

Безопасность элемента управления 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. Url Свойство

Определение

Возвращает или задает URL-адрес текущего документа. Gets or sets the URL of the current document.

Значение свойства

Объект Uri, представляющий URL-адрес текущего документа. A Uri representing the URL of the current document.

Исключения

Данный экземпляр 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.

Указанное значение, когда для этого свойства задается неабсолютный универсальный код ресурса (URI). The specified value when setting this property is not an absolute URI. Для получения дополнительной информации см. IsAbsoluteUri. For more information, see IsAbsoluteUri.

Читайте также:  Как сглаженный шрифт windows

Примеры

В следующем примере кода показано, как использовать Url свойство для реализации адресной строки для WebBrowser элемента управления. The following code example demonstrates how to use the Url property to implement an address bar for the WebBrowser control. В этом примере предполагается, что форма содержит WebBrowser элемент управления с именем webBrowser1 , TextBox элемент управления TextBoxAddress и Button элемент управления с именем ButtonGo . This example requires that your form contains a WebBrowser control called webBrowser1 , a TextBox control called TextBoxAddress , and a Button control called ButtonGo . При вводе URL-адреса в текстовое поле и нажатии клавиши ВВОД или нажатии кнопки Go WebBrowser элемент управления переходит по указанному URL-адресу. When you type a URL into the text box and press ENTER or click the Go button, the WebBrowser control navigates to the URL specified. При переходе по гиперссылке текстовое поле автоматически обновляется для вывода текущего URL-адреса. When you navigate by clicking a hyperlink, the text box automatically updates to display the current URL.

Комментарии

Установка этого свойства эквивалентна вызову Navigate метода и передаче ему указанного URL-адреса. Setting this property is equivalent to calling the Navigate method and passing it the specified URL.

WebBrowserЭлемент управления ведет список журналов всех веб-страниц, посещенных во время сеанса просмотра. The WebBrowser control maintains a history list of all the Web pages visited during a browsing session. При задании Url свойства WebBrowser элемент управления переходит по указанному URL-адресу и добавляет его в конец списка журнала. When you set the Url property, the WebBrowser control navigates to the specified URL and adds it to the end of the history list.

WebBrowserЭлемент управления хранит веб-страницы с недавно посещенных сайтов в кэше на локальном жестком диске. The WebBrowser control stores Web pages from recently visited sites in a cache on the local hard disk. На каждой странице можно указать дату окончания срока действия, указывающую, как долго она будет оставаться в кэше. Each page can specify an expiration date indicating how long it will remain in the cache. Когда элемент управления переходит на страницу, он экономит время, отображая кэшированную версию, если она доступна, а не загружает ее снова. When the control navigates to a page, it saves time by displaying a cached version, if one is available, rather than downloading the page again. Используйте Refresh метод, чтобы принудительно WebBrowser перезагрузить текущую страницу элементом управления, загрузив его, убедившись, что элемент управления отображает последнюю версию. Use the Refresh method to force the WebBrowser control to reload the current page by downloading it, ensuring that the control displays the latest version.

Это свойство содержит URL-адрес текущего документа, даже если был запрошен другой документ. This property contains the URL 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 document. Новое значение можно получить в DocumentCompleted обработчике событий. You can retrieve the new value in a DocumentCompleted event handler.

Оцените статью