The most complete C# Webbrowser wrapper control – CodeProject

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 interfaces
  • IOleInPlaceSite – required as part of Webbrowser control hosting interfaces
  • IDocHostShowUI – to handle ::ShowMessage
  • IDocHostUIHandler – to handle ::ShowContextMenu, ::TranslateAccelerator, ::GetOptionKeyPath, ::GetDropTarget and ::GetHostInfo
  • DWebBrowserEvents2 – to handle Webbrowser events
  • IDropTarget – to handle full drag drop internally
  • IServiceProvider – to handle ::QryService
  • IHttpSecurity – to handle HTTP-related security problems
  • IWindowForBindingUI – returns a handle via ::GetWindow that is used by MSHTML to display information in client UI
  • INewWindowManager – WinX sp2 and up, to handle popups
  • IAuthenticate – to handle basic and NTLM authentication
  • IOleCommandTarget – to intercept script errors via the ::Exec method
  • IinternetSecurityManager – to handle ::ProcessUrlAction
  • IHTMLEventCallBack – A callback mechanism to pass HTMLDocument and HTMLWindow events to the control and, in turn, to the client
  • IProtectFocus – IE7 + Vista – Qries for permission to grab the focus when loading the page or when a script attempts to focus an element
  • IHTMLOMWindowServices – 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

  • WBDOCDOWNLOADCTLFLAGget setDOC_DOWNLOAD_CONTROL_FLAGS
  • DownloadImagesget set – shortcut for DOCDOWNLOADCTLFLAG.DLIMAGES
  • DownloadSoundsget set – shortcut for DOCDOWNLOADCTLFLAG.BGSOUNDS
  • DownloadActiveXget set – shortcut for DOCDOWNLOADCTLFLAG.NO_DLACTIVEXCTLS
  • DownloadJavaget set – shortcut for DOCDOWNLOADCTLFLAG.NO_JAVA
  • DownloadFramesget set – shortcut for DOCDOWNLOADCTLFLAG.NO_FRAMEDOWNLOAD
  • DownloadScriptsget set – shortcut for DOCDOWNLOADCTLFLAG.NO_SCRIPTS
  • WBDOCHOSTUIFLAGget set DOC_HOST_UI_FLAGS
  • Border3DEnabledget set – Webbrowser 3D border
  • ScrollBarsEnabledget set – Webbrowser Scrollbars
  • WBDOCHOSTUIDBLCLKget set DOC_HOST_UI_DBLCLK
  • TextSizeget set – Webbrowser zoom property
  • CanGoBackget – can navigate backward
  • CanGoForwardget – can navigate forward
  • WebbrowserObjectget – Document object of Webbrowser control
  • SendSourceOnDocumentCompleteWBExget set – fires DocumentCompleteEX event rather than DocumentComplete. DocumentCompleteEX event has one additional parameter that contains the source of the pDisp document object at the time DocmentComplete was called
  • IEServerHwndget – Internet Explorer_Server HWND
  • ShellEmbedingHwndget ShellEmbedding HWND
  • ShellDocObjectHwndget ShellDocObject HWND
  • RegisterAsDropTargetget set – Webbrowser default drag drop
  • RegisterForInternalDragDropget set – Instr ts the control to take over drag drop. Uses WBDragxxx and WBDropxxx events to notify the client
  • RegisterAsBrowserget set – Registers Webbrowser as a top-level browser for target name resolution
  • Silentget set – whether the Webbrowser control can show dialog boxes
  • LocationNameget – name of the resource that Webbrowser control is currently displaying
  • LocationUrlget set – URL of the resource that Webbrowser control is currently displaying
  • Busyget – indicating whether the Webbrowser control is engaged in a navigation or downloading operation
  • OffLineget set – currently operating in offline mode
  • ReadyStateget – retrieves Readystate of the Webbrowser control
  • ThumbImageget – Contains a thumb image of the Webbrowser or null
  • ObjectForScripting property. Allows JavaScript functions in an HTML page to call methods and properties of a an instance class passed to this property. Same as ObjectForScripting of C# Webbrowser wrapper control. An example of how to use this property has been provided in WinExternal class of frmMain
  • DocumentTitleSets or retrieves the title of the document
  • DocumentSourceSets or retrieves the HTML source of the document
  • UseInternalDownloadManagerSet to tr, default, to allow the control to take over file downloads. FileDownloadExxxx events are fired instead of FileDownload event. This functionality is achieved via COM library which implements IDownloadManager interface. The download routines account for redirect and Content_Disposition header
  • FileDownloadDirectory Default file download directory. Set to users MyDocuments folder by default. Used only if UseInternalDownloadManager property is set to tr

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 using IPersistMoniker interface
  • p lic bool LoadHtmlIntoBrowser(string html, string sBaseUrl) – Loads HTML content into browser using LoadHTMLMoniker class and IPersistMoniker interface, allowing client to set the baseurl
  • p lic bool LoadHtmlIntoBrowser(string html) – Loads HTML content into browser using IPersistStreamInit interface, baseurl, is set to about:blank by MSHTML
  • p lic void ShowCertificateDialog() – If available, displays certificate for current website
  • p 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 Zorder
  • p lic Image DrawThumb2(int W, int H, System.Drawing.Imaging.PixelFormat pixFormat) – Uses IViewObject interface obtained from IHTMLDocument2 to draw a thumb image of the Webbrowser control
  • p lic void SaveBrowserImage(string sFileName, System.Drawing.Imaging.PixelFormat pixFormat, System.Drawing.Imaging.ImageFormat format) – Saves Webbrowser image
  • p 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. Returns tr if found, else false. 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 for IHTMLDocument2::qryCommandEnabled
  • p lic bool SetDesignMode(string sMode)
  • p lic string GetDesignMode()
  • p lic IHTMLElement GetActiveElement() – Returns the active element or null. Accounts for frames
  • p lic IHTMLDocument2 GetActiveDocument() – Returns the active document or null. Accounts for frames
  • p lic string GetTitle(bool bTopLevel) – Wrapper for IHtmlDocument2::title
  • p lic string GetTitle(IWebBrowser2 thisBrowser)
  • p lic string GetText(bool bTopLevel) – Wrapper for IHTMLDocument3::outerText
  • p lic string GetText(IWebBrowser2 thisBrowser)
  • p lic string GetSource(bool bTopLevel) – Wrapper for IHTMLDocument3::outerHTML
  • p lic string GetSource(IWebBrowser2 thisBrowser)
  • p lic IHTMLElementCollection GetImages(bool bTopLevel) – Wrapper for IHTMLDocument2::images
  • p lic IHTMLElementCollection GetAnchors(bool bTopLevel) – Wrapper for IHTMLDocument2::anchors
  • p 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 for IHTMLDocument2::elementFromPoint
  • p lic bool ExecCommand(bool bTopLevel, string CmdId) – Wrapper for IHTMLDocument2::execCommand
  • p lic bool QryCommandState(bool bTopLevel, string CmdId) – Wrapper for IHTMLDocument2::qryCommandState
  • p lic bool OleCommandExec(bool bTopLevel, MSHTML_COMMAND_IDS CmdID) – Wrapper for IHTMLDocument2::IOleCommandTarget::Exec
  • p lic object QryCommandVal(string CmdID) – Wrapper for IHTMLDocument2::qryCommandVal
  • p lic bool QryCommandState(bool bTopLevel, string CmdId) – Wrapper for IHTMLDocument2::qryCommandState
  • p lic IHTMLElement GetElementByID(bool bTopLevel, string idval) – Wrapper for IHTMLDocument3::getElementById
  • p lic IHTMLElementCollection GetElementsByTagName(bool bTopLevel, String tagname) – Wrapper for IHTMLDocument3::getElementsByTagName
  • p lic IHTMLElementCollection GetElementsByName(bool bTopLevel, string elemname) – Wrapper for IHTMLDocument3::getElementsByName
  • p lic object execScript(bool bTopLevel, string ScriptName, string ScriptLang ge) – Wrapper for IHTMLWindow2::execScript
  • p lic bool OleCommandExec(bool bTopLevel, MSHTML_COMMAND_IDS CmdID, object pvaIn) – Wrapper for IHTMLWindow2::execScript, which accepts a parameter
  • p lic object InvokeScript(string ScriptName, object[] Data) – Invokes a script within the HTML page
  • p lic object InvokeScript(IWebBrowser2 wb, string ScriptName, object[] Data) – Invokes a script within the HTML page
  • p lic bool IsFrameset()
  • p lic int FramesCount()
  • p lic List<IWebBrowser2> GetFrames() – Returns a List populated with the IWebbrowser interfaces of the frames
  • p lic bool CreateInternetShortCut(string LocalFileName, string URL, string Description, string IconFileName, int IconIndex) – Attempts to create an Internet shortcut
  • p lic string ResolveInternetShortCut(string InternetShortCutPath) – Attempts to resolve an Internet shortcut
  • p lic bool ClearHistory() – Clears IE history
  • p lic void ActivateHTMLEvents(HTMLEventType EventType, int[] HTMLEventDispIds) – Activates either HTMLdocument or HTMLWindow events
  • p lic void DeactivateHTMLEvents(HTMLEventType EventType) – Deactivates previously activated HTMLDocument or HTMLwindow events
  • p lic int DownloadFile(string Url) Attempts to download a file asynch. FileDownloadExXXX events are used for notifications. Return val is a uniq ID for this download that can be used to stop the download
  • p lic void StopFileDownload(int dlUID) Stops a file download that was started by calling the DownloadFile method
  • p lic void StartHTTPAPP() Call to start receiving HTTP reqst and response headers via ProtocolHandlerOnResponse and ProtocolHandlerOnBeginTransaction events
  • p lic void StopHTTPAPP() Call to stop ProtocolHandlerOnResponse and ProtocolHandlerOnBeginTransaction events for HTTP protocol
  • p lic void StopHTTPSAPP() Call to stop ProtocolHandlerOnResponse and ProtocolHandlerOnBeginTransaction events for HTTPS protocol
  • p lic void StartHTTPSAPP() Call to start receiving HTTPS reqst and response headers via ProtocolHandlerOnResponse and ProtocolHandlerOnBeginTransaction events
  • void SetAllowHTMLDialogs() – default tr set allow or disallow flag for HTML dialogs launched using showModelessDialog() and showModalDialog() methods using CBT Window Hook
  • bool GetAllowHTMLDialogs()get allow or disallow flag for HTML dialogs launched using showModelessDialog() and showModalDialog() methods using CBT Window Hook
  • p lic bool AutomationTask_PerformClickButton(string btnname) – Performs a click on a Button element with given name
  • p lic bool AutomationTask_PerformClickLink(string linkname) – Performs a click on a Link element with given name
  • p lic bool AutomationTask_PerformEnterData(string inputname, string strVal) – Enters strVal into an input element with given name
  • p lic bool AutomationTask_PerformEnterDataTextArea(string inputname, string strVal) – Enters strVal into a textarea element with given name
  • p lic bool AutomationTask_PerformS mitForm(string formname) – S mits a form with given name
  • p lic bool AutomationTask_PerformSelectList(string selectname, string listitemval) – Selects a list item element with given listitemval
  • AutomationTask_PerformSelectRadio(string radioname) – Selects a radio or checkbox element with given radioname

Events

DWebBrowserEvents2

DocumentComplete has been modified to incl? an extra parameter, IsTopLevel, which indicates whether or not we have the top-level document.

  • DocumentComplete
  • BeforeNavigate2
  • ClientToHostWindow
  • CommandStateChange
  • DownloadBegin
  • DownloadComplete
  • FileDownload
  • NavigateComplete2
  • NavigateError
  • NewWindow2
  • NewWindow3
  • PrintTemplateInstantiation
  • PrintTemplateTeardown
  • PrivacyImpactedStateChange
  • ProgressChange
  • PropertyChange
  • SetSecureLockIcon
  • StatusTextChange
  • TitleChange
  • WindowClosing
  • WindowSetHeight
  • WindowSetLeft
  • WindowSetResizable
  • WindowSetTop
  • WindowSetWidth
  • UpdatePageStatus

Drag drop

To use internal drag drop functionality, RegisterForInternalDragDrop must be set to tr (default)

  • WBDragEnter
  • WBDragLeave
  • WBDragOver
  • WBDragDrop

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 useful
  • WBKeyUp
  • WBContextMenu – Handle context menus
  • WBGetOptionKeyPath – Allows the client to set up their own registry settings for Webbrowser control to use
  • WBDocHostShowUIShowMessage – Allows interception of messageboxes
  • DocumentCompleteEX – Setting SendSourceOnDocumentCompleteWBEx property will cause this event to fire instead of DocumentComplete, passing an extra parameter that contains the source of the document
  • WBAuthenticate – Fires for basic and NTLM authentications. For NTLM, client needs to pass credentials as Username = Domainusername
  • WBSecurityProblem – Fires when WinInet encounters a security problem
  • WBEvaluteNewWindow – XPsp2, replaces NewWindowx events
  • RefreshBegin
  • RefreshEnd
  • ScriptError – Fires for script errors. Contains all details in regard to script error
  • ProcessUrlAction – Policy based URL processing
  • HTMLEvent – Only event handler for HTMLDocument and HTMLwindow events
  • FileDownloadExStart – If UseInternalDownloadManager tr, 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 mechanism
  • FileDownloadExEnd – If UseInternalDownloadManager tr, notifies client of end of a file download
  • FileDownloadExProgress – If UseInternalDownloadManager tr, notifies client of status of a file download
  • FileDownloadExAuthenticate – If UseInternalDownloadManager tr, notifies client of a reqst from server for authentication
  • FileDownloadExError – If UseInternalDownloadManager tr, notifies client of an error during a file download
  • ProtocolHandlerOnBeginTransaction Enables the client to view all the HTTP and HTTPS reqst headers of Webbrowser control
  • ProtocolHandlerOnResponse Enables the client to view all HTTP and HTTPS the response headers of Webbrowser control
  • AllowFocusChange – IE7 Vista – notify client when focus is being changed via implementation of IProtectFocus interface
  • HTMLOMWindowServices_moveToIHTMLOMWindowServices implementation – Moves the screen position of the upper-left corner of the application window to the specified coordinates
  • HTMLOMWindowServices_moveByIHTMLOMWindowServices implementation – Moves the screen position of the application window by the specified offset vals
  • HTMLOMWindowServices_resizeToIHTMLOMWindowServices implementation – Changes the current size of the application window by the specified offset vals.
  • HTMLOMWindowServices_resizeByIHTMLOMWindowServices implementation – Sets the size of the application window to the specified vals

引文来源  The most complete C# Webbrowser wrapper control – CodeProject