Interfaces
Each interface mentioned below plays a role in either the hosting or customization process. I decided not to go through a detailed explanation of how to implement and use the interfaces. One can easily find all of the information regarding implementation and functionalities offered by these interfaces from MSDN, or right here on this site.
IOleClientSite– required as part of Webbrowser control hosting interfacesIOleInPlaceSite– required as part of Webbrowser control hosting interfacesIDocHostShowUI– to handle::ShowMessageIDocHostUIHandler– to handle::ShowContextMenu,::TranslateAccelerator,::GetOptionKeyPath,::GetDropTargetand::GetHostInfoDWebBrowserEvents2– to handle Webbrowser eventsIDropTarget– to handle full drag drop internallyIServiceProvider– to handle::QryServiceIHttpSecurity– to handle HTTP-related security problemsIWindowForBindingUI– returns a handle via::GetWindowthat is used by MSHTML to display information in client UIINewWindowManager– WinX sp2 and up, to handle popupsIAuthenticate– to handle basic and NTLM authenticationIOleCommandTarget– to intercept script errors via the::ExecmethodIinternetSecurityManager– to handle::ProcessUrlActionIHTMLEventCallBack– A callback mechanism to passHTMLDocumentandHTMLWindowevents to the control and, in turn, to the clientIProtectFocus– IE7 + Vista – Qries for permission to grab the focus when loading the page or when a script attempts to focus an elementIHTMLOMWindowServices– XP sp2 – Enables applications that are hosting the WebBrowser Control to intercept the window object calls for manipulating the host window coordinates from Dynamic HTML (DHTML) script
Properties
WBDOCDOWNLOADCTLFLAG–get set–DOC_DOWNLOAD_CONTROL_FLAGSDownloadImages–get set– shortcut forDOCDOWNLOADCTLFLAG.DLIMAGESDownloadSounds–get set– shortcut forDOCDOWNLOADCTLFLAG.BGSOUNDSDownloadActiveX–get set– shortcut forDOCDOWNLOADCTLFLAG.NO_DLACTIVEXCTLSDownloadJava–get set– shortcut forDOCDOWNLOADCTLFLAG.NO_JAVADownloadFrames–get set– shortcut forDOCDOWNLOADCTLFLAG.NO_FRAMEDOWNLOADDownloadScripts–get set– shortcut forDOCDOWNLOADCTLFLAG.NO_SCRIPTSWBDOCHOSTUIFLAG–get set–DOC_HOST_UI_FLAGSBorder3DEnabled–get set– Webbrowser 3D borderScrollBarsEnabled–get set– Webbrowser ScrollbarsWBDOCHOSTUIDBLCLK–get set–DOC_HOST_UI_DBLCLKTextSize–get set– Webbrowser zoom propertyCanGoBack–get– can navigate backwardCanGoForward–get– can navigate forwardWebbrowserObject–get– Document object of Webbrowser controlSendSourceOnDocumentCompleteWBEx–get set– firesDocumentCompleteEXevent rather thanDocumentComplete.DocumentCompleteEXevent has one additional parameter that contains the source of thepDispdocument object at the timeDocmentCompletewas calledIEServerHwnd–get– InternetExplorer_ServerHWNDShellEmbedingHwnd–get–ShellEmbeddingHWNDShellDocObjectHwnd–get–ShellDocObjectHWNDRegisterAsDropTarget–get set– Webbrowser default drag dropRegisterForInternalDragDrop–get set– Instr ts the control to take over drag drop. UsesWBDragxxxandWBDropxxxevents to notify the clientRegisterAsBrowser–get set– Registers Webbrowser as a top-level browser for target name resolutionSilent–get set– whether the Webbrowser control can show dialog boxesLocationName–get– name of the resource that Webbrowser control is currently displayingLocationUrl–get set– URL of the resource that Webbrowser control is currently displayingBusy–get– indicating whether the Webbrowser control is engaged in a navigation or downloading operationOffLine–get set– currently operating in offline modeReadyState–get– retrievesReadystateof the Webbrowser controlThumbImage–get– Contains a thumb image of the Webbrowser ornullObjectForScriptingproperty. Allows JavaScript functions in an HTML page to call methods and properties of a an instance class passed to this property. Same asObjectForScriptingof C# Webbrowser wrapper control. An example of how to use this property has been provided inWinExternalclass offrmMainDocumentTitle–Sets or retrieves the title of the documentDocumentSource–Sets or retrieves the HTML source of the documentUseInternalDownloadManager–Settotr, default, to allow the control to take over file downloads.FileDownloadExxxxevents are fired instead ofFileDownloadevent. This functionality is achieved via COM library which implementsIDownloadManagerinterface. The download routines account for redirect andContent_DispositionheaderFileDownloadDirectoryDefault file download directory.Setto users MyDocuments folder by default. Used only ifUseInternalDownloadManagerproperty is set totr
Methods
Basic
These methods are self explanatory
p lic void Navigate(string URL)p lic void Navigate(string URL, BrowserNavConstants Flags)p lic void Navigate(string URL, BrowserNavConstants Flags, string TargetFrameName)p lic void Navigate(string URL, BrowserNavConstants Flags, string PostData)p lic void Navigate(string URL, string PostData)p lic void Navigate(string URL, byte[] PostData)p lic void Navigate2(string URL)p lic void Stop()p lic bool GoBack()p lic bool GoForward()p lic void GoHome()p lic void GoSearch()p lic void Refresh2(RefreshConstants Level)p lic bool SelectAll()p lic bool Clear()p lic bool ClearSelection()p lic bool Copy()p lic bool Paste()p lic bool Cut()p lic bool Undo()p lic bool Redo()p lic bool Delete()p lic bool PasteSpecial()p lic bool Spell()p lic bool NewWindow()p lic bool Print()p lic bool Print2()p lic bool Properties()p lic bool PrintPreview()p lic bool PrintPreview2()p lic bool PageSetup()p lic void SaveAs()p lic bool Find()p lic bool IEOptions()p lic bool ViewSource()p lic void OrganizeFavorites()p lic void PrivacySettings()p lic void Lang geDialog()p lic void ProgramAccessAndDefaults()p lic void AddToFavorites()p lic void ImportExport()p lic void SendLinkByEmail()p lic void SendPageByEmail()p lic void SendShortcutToDesktop()
Extended
Note: In a frameset, the bTopLevel parameter determines whether to use the top level document or to attempt to find and use the active document
p lic bool LoadUrlIntoBrowser(String url)– Loads a URL into browser usingIPersistMonikerinterfacep lic bool LoadHtmlIntoBrowser(string html, string sBaseUrl)– Loads HTML content into browser usingLoadHTMLMonikerclass andIPersistMonikerinterface, allowing client to set thebaseurlp lic bool LoadHtmlIntoBrowser(string html)– Loads HTML content into browser usingIPersistStreamInitinterface,baseurl, is set toabout:blankby MSHTMLp lic void ShowCertificateDialog()– If available, displays certificate for current websitep lic Image DrawThumb(int W, int H, System.Drawing.Imaging.PixelFormat pixFormat)– Uses IE_Server HWND to draw a thumb image of the Webbrowser control. Faster than other methods with one draw back. It only works if the Webbrowser control is in front of Zorderp lic Image DrawThumb2(int W, int H, System.Drawing.Imaging.PixelFormat pixFormat)– UsesIViewObjectinterface obtained fromIHTMLDocument2to draw a thumb image of the Webbrowser controlp lic void SaveBrowserImage(string sFileName, System.Drawing.Imaging.PixelFormat pixFormat, System.Drawing.Imaging.ImageFormat format)– Saves Webbrowser imagep lic bool HasFocus()p lic void SetFocus()p lic void SetFocusBody()p lic bool FindInPage(string sFind, bool DownWard, bool MatchWholeWord, bool MatchCase, bool ScrollIntoView)– Finds a match. Returnstrif found, elsefalse. In a frameset, it attempts to find and use the active document.p lic int FindAndHightAllInPage(string sFind, bool MatchWholeWord, bool MatchCase, int cbackColor, int cForeColor)– Finds and highlights all matches. Returns number of matches found. In a frameset, it attempts to find and use the active document.p lic int FindAndHightAllInPage(string sFind, bool MatchWholeWord, bool MatchCase, string cbackColor, string cForeColor)p lic int FindAndHightAllInPage(string sFind, bool MatchWholeWord, bool MatchCase, Color cbackColor, Color cForeColor)p lic bool IsCommandEnabled(string sCmdId)– Wrapper forIHTMLDocument2::qryCommandEnabledp lic bool SetDesignMode(string sMode)p lic string GetDesignMode()p lic IHTMLElement GetActiveElement()– Returns the active element ornull. Accounts for framesp lic IHTMLDocument2 GetActiveDocument()– Returns the active document ornull. Accounts for framesp lic string GetTitle(bool bTopLevel)– Wrapper forIHtmlDocument2::titlep lic string GetTitle(IWebBrowser2 thisBrowser)p lic string GetText(bool bTopLevel)– Wrapper forIHTMLDocument3::outerTextp lic string GetText(IWebBrowser2 thisBrowser)p lic string GetSource(bool bTopLevel)– Wrapper forIHTMLDocument3::outerHTMLp lic string GetSource(IWebBrowser2 thisBrowser)p lic IHTMLElementCollection GetImages(bool bTopLevel)– Wrapper forIHTMLDocument2::imagesp lic IHTMLElementCollection GetAnchors(bool bTopLevel)– Wrapper forIHTMLDocument2::anchorsp lic string GetSelectedText(bool bTopLevel, bool ReturnAsHTML)– Returns selection as plain text or HTML.p lic IHTMLElement ElementFromPoint(bool bTopLevel, int X, int Y)– Wrapper forIHTMLDocument2::elementFromPointp lic bool ExecCommand(bool bTopLevel, string CmdId)– Wrapper forIHTMLDocument2::execCommandp lic bool QryCommandState(bool bTopLevel, string CmdId)– Wrapper forIHTMLDocument2::qryCommandStatep lic bool OleCommandExec(bool bTopLevel, MSHTML_COMMAND_IDS CmdID)– Wrapper forIHTMLDocument2::IOleCommandTarget::Execp lic object QryCommandVal(string CmdID)– Wrapper forIHTMLDocument2::qryCommandValp lic bool QryCommandState(bool bTopLevel, string CmdId)– Wrapper forIHTMLDocument2::qryCommandStatep lic IHTMLElement GetElementByID(bool bTopLevel, string idval)– Wrapper forIHTMLDocument3::getElementByIdp lic IHTMLElementCollection GetElementsByTagName(bool bTopLevel, String tagname)– Wrapper forIHTMLDocument3::getElementsByTagNamep lic IHTMLElementCollection GetElementsByName(bool bTopLevel, string elemname)– Wrapper forIHTMLDocument3::getElementsByNamep lic object execScript(bool bTopLevel, string ScriptName, string ScriptLang ge)– Wrapper forIHTMLWindow2::execScriptp lic bool OleCommandExec(bool bTopLevel, MSHTML_COMMAND_IDS CmdID, object pvaIn)– Wrapper forIHTMLWindow2::execScript, which accepts a parameterp lic object InvokeScript(string ScriptName, object[] Data)– Invokes a script within the HTML pagep lic object InvokeScript(IWebBrowser2 wb, string ScriptName, object[] Data)– Invokes a script within the HTML pagep lic bool IsFrameset()p lic int FramesCount()p lic List<IWebBrowser2> GetFrames()– Returns a List populated with theIWebbrowserinterfaces of the framesp lic bool CreateInternetShortCut(string LocalFileName, string URL, string Description, string IconFileName, int IconIndex)– Attempts to create an Internet shortcutp lic string ResolveInternetShortCut(string InternetShortCutPath)– Attempts to resolve an Internet shortcutp lic bool ClearHistory()– Clears IE historyp lic void ActivateHTMLEvents(HTMLEventType EventType, int[] HTMLEventDispIds)– Activates eitherHTMLdocumentorHTMLWindoweventsp lic void DeactivateHTMLEvents(HTMLEventType EventType)– Deactivates previously activatedHTMLDocumentorHTMLwindoweventsp lic int DownloadFile(string Url)Attempts to download a file asynch.FileDownloadExXXXevents are used for notifications. Return val is a uniq ID for this download that can be used to stop the downloadp lic void StopFileDownload(int dlUID)Stops a file download that was started by calling theDownloadFilemethodp lic void StartHTTPAPP()Call to start receiving HTTP reqst and response headers viaProtocolHandlerOnResponseandProtocolHandlerOnBeginTransactioneventsp lic void StopHTTPAPP()Call to stopProtocolHandlerOnResponseandProtocolHandlerOnBeginTransactionevents for HTTP protocolp lic void StopHTTPSAPP()Call to stopProtocolHandlerOnResponseandProtocolHandlerOnBeginTransactionevents for HTTPS protocolp lic void StartHTTPSAPP()Call to start receiving HTTPS reqst and response headers viaProtocolHandlerOnResponseandProtocolHandlerOnBeginTransactioneventsvoid SetAllowHTMLDialogs()– defaulttr–setallow or disallow flag for HTML dialogs launched usingshowModelessDialog()andshowModalDialog()methods usingCBTWindow Hookbool GetAllowHTMLDialogs()–getallow or disallow flag for HTML dialogs launched usingshowModelessDialog()andshowModalDialog()methods usingCBTWindow Hookp lic bool AutomationTask_PerformClickButton(string btnname)– Performs a click on aButtonelement with given namep lic bool AutomationTask_PerformClickLink(string linkname)– Performs a click on aLinkelement with given namep lic bool AutomationTask_PerformEnterData(string inputname, string strVal)– EntersstrValinto an input element with given namep lic bool AutomationTask_PerformEnterDataTextArea(string inputname, string strVal)– Enters strVal into a textarea element with given namep lic bool AutomationTask_PerformS mitForm(string formname)– S mits a form with given namep lic bool AutomationTask_PerformSelectList(string selectname, string listitemval)– Selects a list item element with givenlistitemvalAutomationTask_PerformSelectRadio(string radioname)– Selects a radio or checkbox element with givenradioname
Events
DWebBrowserEvents2
DocumentComplete has been modified to incl? an extra parameter, IsTopLevel, which indicates whether or not we have the top-level document.
DocumentCompleteBeforeNavigate2ClientToHostWindowCommandStateChangeDownloadBeginDownloadCompleteFileDownloadNavigateComplete2NavigateErrorNewWindow2NewWindow3PrintTemplateInstantiationPrintTemplateTeardownPrivacyImpactedStateChangeProgressChangePropertyChangeSetSecureLockIconStatusTextChangeTitleChangeWindowClosingWindowSetHeightWindowSetLeftWindowSetResizableWindowSetTopWindowSetWidthUpdatePageStatus
Drag drop
To use internal drag drop functionality, RegisterForInternalDragDrop must be set to tr (default)
WBDragEnterWBDragLeaveWBDragOverWBDragDrop
Extended
FileDownloadExXXX events are activated by setting UseInternalDownloadManager property to tr (default)
WBKeyDown– Rather than just firing when accelerator keys are used, I have decided to intercept key down and up, which I find to be more usefulWBKeyUpWBContextMenu– Handle context menusWBGetOptionKeyPath– Allows the client to set up their own registry settings for Webbrowser control to useWBDocHostShowUIShowMessage– Allows interception of messageboxesDocumentCompleteEX– SettingSendSourceOnDocumentCompleteWBExproperty will cause this event to fire instead ofDocumentComplete, passing an extra parameter that contains the source of the documentWBAuthenticate– Fires for basic and NTLM authentications. For NTLM, client needs to pass credentials as Username = DomainusernameWBSecurityProblem– Fires when WinInet encounters a security problemWBEvaluteNewWindow– XPsp2, replacesNewWindowxeventsRefreshBeginRefreshEndScriptError– Fires for script errors. Contains all details in regard to script errorProcessUrlAction– Policy based URL processingHTMLEvent– Only event handler forHTMLDocumentandHTMLwindoweventsFileDownloadExStart– IfUseInternalDownloadManagertr, notifies client of a reqst to start a file download. Stop download at any point using a uniq ID, save file in the background. Overrides Webbrowser default file download mechanismFileDownloadExEnd– IfUseInternalDownloadManagertr, notifies client of end of a file downloadFileDownloadExProgress– IfUseInternalDownloadManagertr, notifies client of status of a file downloadFileDownloadExAuthenticate– IfUseInternalDownloadManagertr, notifies client of a reqst from server for authenticationFileDownloadExError– IfUseInternalDownloadManagertr, notifies client of an error during a file downloadProtocolHandlerOnBeginTransactionEnables the client to view all the HTTP and HTTPS reqst headers of Webbrowser controlProtocolHandlerOnResponseEnables the client to view all HTTP and HTTPS the response headers of Webbrowser controlAllowFocusChange– IE7 Vista – notify client when focus is being changed via implementation ofIProtectFocusinterfaceHTMLOMWindowServices_moveTo–IHTMLOMWindowServicesimplementation – Moves the screen position of the upper-left corner of the application window to the specified coordinatesHTMLOMWindowServices_moveBy–IHTMLOMWindowServicesimplementation – Moves the screen position of the application window by the specified offset valsHTMLOMWindowServices_resizeTo–IHTMLOMWindowServicesimplementation – Changes the current size of the application window by the specified offset vals.HTMLOMWindowServices_resizeBy–IHTMLOMWindowServicesimplementation – Sets the size of the application window to the specified vals
引文来源 The most complete C# Webbrowser wrapper control – CodeProject