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::ShowMessage
IDocHostUIHandler
– to handle::ShowContextMenu
,::TranslateAccelerator
,::GetOptionKeyPath
,::GetDropTarget
and::GetHostInfo
DWebBrowserEvents2
– to handle Webbrowser eventsIDropTarget
– to handle full drag drop internallyIServiceProvider
– to handle::QryService
IHttpSecurity
– to handle HTTP-related security problemsIWindowForBindingUI
– returns a handle via::GetWindow
that 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::Exec
methodIinternetSecurityManager
– to handle::ProcessUrlAction
IHTMLEventCallBack
– A callback mechanism to passHTMLDocument
andHTMLWindow
events 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_FLAGS
DownloadImages
–get set
– shortcut forDOCDOWNLOADCTLFLAG.DLIMAGES
DownloadSounds
–get set
– shortcut forDOCDOWNLOADCTLFLAG.BGSOUNDS
DownloadActiveX
–get set
– shortcut forDOCDOWNLOADCTLFLAG.NO_DLACTIVEXCTLS
DownloadJava
–get set
– shortcut forDOCDOWNLOADCTLFLAG.NO_JAVA
DownloadFrames
–get set
– shortcut forDOCDOWNLOADCTLFLAG.NO_FRAMEDOWNLOAD
DownloadScripts
–get set
– shortcut forDOCDOWNLOADCTLFLAG.NO_SCRIPTS
WBDOCHOSTUIFLAG
–get set
–DOC_HOST_UI_FLAGS
Border3DEnabled
–get set
– Webbrowser 3D borderScrollBarsEnabled
–get set
– Webbrowser ScrollbarsWBDOCHOSTUIDBLCLK
–get set
–DOC_HOST_UI_DBLCLK
TextSize
–get set
– Webbrowser zoom propertyCanGoBack
–get
– can navigate backwardCanGoForward
–get
– can navigate forwardWebbrowserObject
–get
– Document object of Webbrowser controlSendSourceOnDocumentCompleteWBEx
–get set
– firesDocumentCompleteEX
event rather thanDocumentComplete
.DocumentCompleteEX
event has one additional parameter that contains the source of thepDisp
document object at the timeDocmentComplete
was calledIEServerHwnd
–get
– InternetExplorer_Server
HWNDShellEmbedingHwnd
–get
–ShellEmbedding
HWNDShellDocObjectHwnd
–get
–ShellDocObject
HWNDRegisterAsDropTarget
–get set
– Webbrowser default drag dropRegisterForInternalDragDrop
–get set
– Instr ts the control to take over drag drop. UsesWBDragxxx
andWBDropxxx
events 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
– retrievesReadystate
of the Webbrowser controlThumbImage
–get
– Contains a thumb image of the Webbrowser ornull
ObjectForScripting
property. Allows JavaScript functions in an HTML page to call methods and properties of a an instance class passed to this property. Same asObjectForScripting
of C# Webbrowser wrapper control. An example of how to use this property has been provided inWinExternal
class offrmMain
DocumentTitle
–Set
s or retrieves the title of the documentDocumentSource
–Set
s or retrieves the HTML source of the documentUseInternalDownloadManager
–Set
totr
, default, to allow the control to take over file downloads.FileDownloadExxxx
events are fired instead ofFileDownload
event. This functionality is achieved via COM library which implementsIDownloadManager
interface. The download routines account for redirect andContent_Disposition
headerFileDownloadDirectory
Default file download directory.Set
to users MyDocuments folder by default. Used only ifUseInternalDownloadManager
property 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 usingIPersistMoniker
interfacep lic bool LoadHtmlIntoBrowser(string html, string sBaseUrl)
– Loads HTML content into browser usingLoadHTMLMoniker
class andIPersistMoniker
interface, allowing client to set thebaseurl
p lic bool LoadHtmlIntoBrowser(string html)
– Loads HTML content into browser usingIPersistStreamInit
interface,baseurl
, is set toabout:blank
by 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)
– UsesIViewObject
interface obtained fromIHTMLDocument2
to 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. Returnstr
if 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::qryCommandEnabled
p 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::title
p lic string GetTitle(IWebBrowser2 thisBrowser)
p lic string GetText(bool bTopLevel)
– Wrapper forIHTMLDocument3::outerText
p lic string GetText(IWebBrowser2 thisBrowser)
p lic string GetSource(bool bTopLevel)
– Wrapper forIHTMLDocument3::outerHTML
p lic string GetSource(IWebBrowser2 thisBrowser)
p lic IHTMLElementCollection GetImages(bool bTopLevel)
– Wrapper forIHTMLDocument2::images
p lic IHTMLElementCollection GetAnchors(bool bTopLevel)
– Wrapper forIHTMLDocument2::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 forIHTMLDocument2::elementFromPoint
p lic bool ExecCommand(bool bTopLevel, string CmdId)
– Wrapper forIHTMLDocument2::execCommand
p lic bool QryCommandState(bool bTopLevel, string CmdId)
– Wrapper forIHTMLDocument2::qryCommandState
p lic bool OleCommandExec(bool bTopLevel, MSHTML_COMMAND_IDS CmdID)
– Wrapper forIHTMLDocument2::IOleCommandTarget::Exec
p lic object QryCommandVal(string CmdID)
– Wrapper forIHTMLDocument2::qryCommandVal
p lic bool QryCommandState(bool bTopLevel, string CmdId)
– Wrapper forIHTMLDocument2::qryCommandState
p lic IHTMLElement GetElementByID(bool bTopLevel, string idval)
– Wrapper forIHTMLDocument3::getElementById
p lic IHTMLElementCollection GetElementsByTagName(bool bTopLevel, String tagname)
– Wrapper forIHTMLDocument3::getElementsByTagName
p lic IHTMLElementCollection GetElementsByName(bool bTopLevel, string elemname)
– Wrapper forIHTMLDocument3::getElementsByName
p lic object execScript(bool bTopLevel, string ScriptName, string ScriptLang ge)
– Wrapper forIHTMLWindow2::execScript
p 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 theIWebbrowser
interfaces 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 eitherHTMLdocument
orHTMLWindow
eventsp lic void DeactivateHTMLEvents(HTMLEventType EventType)
– Deactivates previously activatedHTMLDocument
orHTMLwindow
eventsp 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 downloadp lic void StopFileDownload(int dlUID)
Stops a file download that was started by calling theDownloadFile
methodp lic void StartHTTPAPP()
Call to start receiving HTTP reqst and response headers viaProtocolHandlerOnResponse
andProtocolHandlerOnBeginTransaction
eventsp lic void StopHTTPAPP()
Call to stopProtocolHandlerOnResponse
andProtocolHandlerOnBeginTransaction
events for HTTP protocolp lic void StopHTTPSAPP()
Call to stopProtocolHandlerOnResponse
andProtocolHandlerOnBeginTransaction
events for HTTPS protocolp lic void StartHTTPSAPP()
Call to start receiving HTTPS reqst and response headers viaProtocolHandlerOnResponse
andProtocolHandlerOnBeginTransaction
eventsvoid SetAllowHTMLDialogs()
– defaulttr
–set
allow or disallow flag for HTML dialogs launched usingshowModelessDialog()
andshowModalDialog()
methods usingCBT
Window Hookbool GetAllowHTMLDialogs()
–get
allow or disallow flag for HTML dialogs launched usingshowModelessDialog()
andshowModalDialog()
methods usingCBT
Window Hookp lic bool AutomationTask_PerformClickButton(string btnname)
– Performs a click on aButton
element with given namep lic bool AutomationTask_PerformClickLink(string linkname)
– Performs a click on aLink
element with given namep lic bool AutomationTask_PerformEnterData(string inputname, string strVal)
– EntersstrVal
into 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 givenlistitemval
AutomationTask_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.
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 usefulWBKeyUp
WBContextMenu
– Handle context menusWBGetOptionKeyPath
– Allows the client to set up their own registry settings for Webbrowser control to useWBDocHostShowUIShowMessage
– Allows interception of messageboxesDocumentCompleteEX
– SettingSendSourceOnDocumentCompleteWBEx
property 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, replacesNewWindowx
eventsRefreshBegin
RefreshEnd
ScriptError
– Fires for script errors. Contains all details in regard to script errorProcessUrlAction
– Policy based URL processingHTMLEvent
– Only event handler forHTMLDocument
andHTMLwindow
eventsFileDownloadExStart
– IfUseInternalDownloadManager
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 mechanismFileDownloadExEnd
– IfUseInternalDownloadManager
tr
, notifies client of end of a file downloadFileDownloadExProgress
– IfUseInternalDownloadManager
tr
, notifies client of status of a file downloadFileDownloadExAuthenticate
– IfUseInternalDownloadManager
tr
, notifies client of a reqst from server for authenticationFileDownloadExError
– IfUseInternalDownloadManager
tr
, notifies client of an error during a file downloadProtocolHandlerOnBeginTransaction
Enables the client to view all the HTTP and HTTPS reqst headers of Webbrowser controlProtocolHandlerOnResponse
Enables 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 ofIProtectFocus
interfaceHTMLOMWindowServices_moveTo
–IHTMLOMWindowServices
implementation – Moves the screen position of the upper-left corner of the application window to the specified coordinatesHTMLOMWindowServices_moveBy
–IHTMLOMWindowServices
implementation – Moves the screen position of the application window by the specified offset valsHTMLOMWindowServices_resizeTo
–IHTMLOMWindowServices
implementation – Changes the current size of the application window by the specified offset vals.HTMLOMWindowServices_resizeBy
–IHTMLOMWindowServices
implementation – Sets the size of the application window to the specified vals
引文来源 The most complete C# Webbrowser wrapper control – CodeProject