C WinForm using WebBrowser
anlaoliu 2021-07-20 07:48:07

C# WinForm WebBrowser ( One ) MSDN Information  

1、 Main uses : Enables the user to navigate the web page in the form .

2、 Be careful :WebBrowser  Control takes up a lot of resources . After using the control, be sure to call  Dispose  Method , To ensure that all resources are released in a timely manner . Must be called on the same thread as the attached event  Dispose  Method , The thread should always be a message or user interface  (UI)  Threads .

3、WebBrowser  Use the following members to navigate the control to a specific  URL、 Move back and forward in the navigation history list , You can also load the current user's home page and search page :

1.URL attribute : Can be read 、 Can write , Used to get or set the  URL.

WebBrowser  Control maintains a history list of all web pages visited during a browsing session . Set up Url Attribute ,WebBrowser  Control to the specified  URL  And put the  URL  Add to the end of the history list .

WebBrowser  Control stores the web pages of recently visited sites in the local hard disk cache . Each page can specify an expiration date , Indicates how long the page remains in the cache . When the control navigates to a page , If the page has a cached version , The contents in the cache are displayed directly without having to download the page again , Thus saving time . Use  Refresh  Method enforcement  WebBrowser Control to reload the current page by downloading , This ensures that the control displays the latest version .

Be careful : Even if another document has been requested , This property also contains the  URL. If you set the value of this property , Then immediately retrieve the value again , If  WebBrowser  Control has not yet had time to load a new document , The retrieved value may be different from the set value .

2.Navigate Method :  Load the document in the specified location into  WebBrowser  Control .

3.GoBack Method : If the previous page in the navigation history is available , Will  WebBrowser  Control to navigate to the page .

If navigation is successful , Then return to true; If the previous page in the navigation history is not available , Then return to false.

 WebBrowser  Control maintains a history list of all web pages visited during a browsing session . have access to GoForward Method to implement a “ back off ” Button .

Use  CanGoBack  Property to determine whether the navigation history is available and whether it contains the previous page . Handle  CanGoBackChanged  event , stay  CanGoBack  Receive notification when property value changes .

4.GoForward Method : If the next page in the navigation history is available , Will  WebBrowser  Control to navigate to the page .

If navigation is successful , Then return to true; If the next page in the navigation history is not available , Then return to false.

WebBrowser  Control maintains a history list of all web pages visited during a browsing session . have access to  GoForward  Method to implement a “ Forward ” Button .

Use  CanGoForward  Property to determine whether navigation history is available and whether it contains pages after the current page . Handle  CanGoForwardChanged  event , stay  CanGoForward  Receive notification when property value changes  

5.GoHome Method : take  WebBrowser  Control to navigate to the current user's home page .

6.GoSearch Method : take  WebBrowser  Control to navigate to the current user's default search page . 

The default search page is stored in the  HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Search Page  Under registry key .

To use a different search page instead of the default search page , Please call  Navigate  Method or assignment  Url  attribute .

7.Refresh Method : Reload the current display in  WebBrowser  Control .

8.Stop Method : Cancels all pending navigation and stops all dynamic page elements ( Such as background sound and animation ).

If the navigation is not successful , A page is displayed to indicate the problem . Using any one of these members to navigate results in different phases of navigation  Navigating、Navigated  and DocumentCompleted  event .


4、ObjectForScripting  attribute : Gets or sets an object , The object can be displayed in the  WebBrowser  Control page contains script code access .

Use this property to enable  WebBrowser  Control and contains  WebBrowser  Control between applications . Use this property to change the dynamic  HTML (DHTML)  Code is integrated with client application code . The object specified for this property can be used as  window.external  object ( Built in for host access  DOM  object ) For web script .

You can set this property to anything you want its public properties and methods to be available to script code  COM  Visible objects . By using  ComVisibleAttribute  Tag a class to make it  COM  Visible classes .

To call a function defined in a web page from the client application code , Please use the  Document  Attribute retrieval  HtmlDocument  Object's  HtmlDocument.InvokeScript  Method .

5、AllowNavigation attribute : Gets or sets a value , This value indicates whether the control can navigate to other pages after loading its initial page .

6、AllowWebBrowserDrop attribute : Gets or sets a value , The value indicates  WebBrowser  Control to navigate to the document you drag and drop onto it .

7、WebBrowserShortcutsEnabled attribute : Is it enabled? WebBrowser Built in shortcut keys .

8、ScriptErrorsSuppressed  attribute : Gets or sets a value , This value indicates when a script error occurs ,WebBrowser  Control to display the error dialog box .

9、IsWebBrowserContextMenuEnabled attribute : Enable right click menu .


Source :MSDN http://msdn.microsoft.com/zh-cn/library/system.windows.forms.webbrowser(v=vs.80).aspx

 

C#WinForm WebBrowser ( Two )  Summary of practical methods  

Practical methods 1: Get status bar information

void webBrowser1_StatusTextChanged(object sender, EventArgs e)
{
    label1.Text = webBrowser1.StatusText;
}

Practical methods 2: Change the address bar address after the page Jump

// stay Navigated It is most appropriate to change the address bar address in the event handler :
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
    textBox1.Text = webBrowser1.Url.ToString();
}

Practical methods 3: Set the radio box

// It is recommended to set the radio box by performing a click event , Instead of modifying properties :
webBrowser1.Document.GetElementById("RBT_A").InvokeMember("click");

Practical methods 4: Set linked drop-down list

// The common linkage multi-level drop-down list is the province / City and county have chosen , In this case, setting the properties of the selection item directly will not trigger linkage , The trigger event function needs to be executed at the end to work properly :

foreach (HtmlElement f in s.GetElementsByTagName("option"))
{
    if (f.InnerText == " Beijing ")
    {
        f.SetAttribute("selected", "selected");
    }
    else
    {
        f.SetAttribute("selected", "");
    }
}
s.RaiseEvent("onchange");

The above four methods are transferred to :http://www.cnblogs.com/SkyD/archive/2009/04/23/1441696.html

Practical method 1 : stay WinForm Corresponding in Web event
hypothesis HTML The source code is as follows :

  

HtmlDocument htmlDoc = webBrowser.Document; 
HtmlElement btnElement = htmlDoc.All["btnClose"]; 
if (btnElement != null) 

    btnElement.click += new HtmlElementEventHandler(HtmlBtnClose_Click); 
}


// Very simple. ? Then it's a little more advanced —— We all know one HTML Elements can have a lot of different kinds of events , and HtmlElement This class gives only the most commonly used 、 Common problems . that , How to respond to other events ? It's also very simple , Just call HtmlElement Of AttachEventHandler That's all right. :

btnElement.AttachEventHandler("onclick", new EventHandler(HtmlBtnClose_Click));  
// This sentence is equivalent to the above btnElement.click += new HtmlElementEventHandler(HtmlBtnClose_Click); 

For other events , hold "onclick" Just change the name of the event . for example :

formElement.AttachEventHandler("onsubmit", new EventHandler(HtmlForm_Submit)); 

  

Practical method 2 : Simulation forms automatically fill in and submit

Suppose you have the simplest login page , Enter the username and password , spot “ Sign in ” Button to log in . Known user name input box id( or Name, The same below ) yes username, Password input box id yes password,“ Sign in ” Button on the id yes submitbutton, Then we just need to webBrowser Of DocumentCompleted Use the following code in the event :

HtmlElement btnSubmit = webBrowser.Document.All["submitbutton"]; 
HtmlElement tbUserid = webBrowser.Document.All["username"]; 
HtmlElement tbPasswd = webBrowser.Document.All["password"]; 

if (tbUserid == null || tbPasswd == null || btnSubmit == null) 
    return; 

tbUserid.SetAttribute("value", "smalldust"); 
tbPasswd.SetAttribute("value", "12345678"); 

btnSubmit.InvokeMember("click");

About form submission , Indeed, there is another way to get form Elements, not button, And use form Elemental submit Method :

HtmlElement formLogin = webBrowser.Document.Forms["loginForm"];  
//……  
formLogin.InvokeMember("submit"); 

The reason why this method is not recommended in this article , Because of the current web page , A lot of them submit Button onclick event , To do the most basic verification of the submitted content . If used directly form Of submit Method , The verification code is not executed , It may cause errors . 

Practical method 3 : Call script

The first is to call Web Functions defined in the script of the page . hypothesis HTML There are the following JavaScript

function DoAdd(a, b) {
    return a + b;
}

that , We will be having WinForm Call it , Just use the following code :

object oSum = webBrowser.Document.InvokeScript("DoAdd", new object[] { 1, 2 });
int sum = Convert.ToInt32(oSum);

 

secondly , If we want to execute a paragraph Web Scripts that didn't exist on the page , How do you do that ? This time, .Net The class for is not provided , It seems that we have to rely on it COM 了 .IHTMLWindow2 Any string can be executed as script code .

string scriptline01 = @"function ShowPageInfo() {";
string scriptline02 = @"     var numLinks = document.links.length; ";
string scriptline03 = @"     var numForms = document.forms.length; ";
string scriptline04 = @"     var numImages = document.images.length; ";
string scriptline05 = @"     var numScripts = document.scripts.length; ";
string scriptline06 = @"     alert(' Web page statistics :\r\n Link number :' + numLinks + ";
string scriptline07 = @"        '\r\n Number of forms :' + numForms + ";
string scriptline08 = @"        '\r\n Number of images :' + numImages + ";
string scriptline09 = @"        '\r\n Number of scripts :' + numScripts);}";
string scriptline10 = @"ShowPageInfo();";

string strScript = scriptline01 + scriptline02 + scriptline03 + scriptline04 + scriptline05 +
                   scriptline06 + scriptline07 + scriptline08 + scriptline09 + scriptline10;

IHTMLWindow2 win = (IHTMLWindow2)webBrowser.Document.Window.DomWindow;
win.execScript(strScript, "javascript");
 

The above three practical methods are transferred to :http://www.cnblogs.com/smalldust/archive/2006/03/08/345561.html

Last : Call in script WinForm Code in , Is this possible ?  ha-ha , It's possible, of course .
The following code example shows how to use  ObjectForScripting  attribute . In this example ,ObjectForScripting  Property is set to the current form .

view sourceprint?

using System; 


using System.Windows.Forms; 

using System.Security.Permissions; 

  


[PermissionSet(SecurityAction.Demand, Name="FullTrust")] 


[System.Runtime.InteropServices.ComVisibleAttribute(true)] 

public class Form1 : Form 


    private WebBrowser webBrowser1 = new WebBrowser(); 

    private Button button1 = new Button(); 


  


    [STAThread] 

    public static void Main() 

    { 


        Application.EnableVisualStyles(); 

        Application.Run(new Form1()); 


    } 

  


    public Form1() 

    { 


        button1.Text = "call script code from client code"; 

        button1.Dock = DockStyle.Top; 


        button1.Click += new EventHandler(button1_Click); 

        webBrowser1.Dock = DockStyle.Fill; 


        Controls.Add(webBrowser1); 

        Controls.Add(button1); 


        Load += new EventHandler(Form1_Load); 

    } 


  


    private void Form1_Load(object sender, EventArgs e) 

    { 


        webBrowser1.AllowWebBrowserDrop = false; 

        webBrowser1.IsWebBrowserContextMenuEnabled = false; 

        webBrowser1.WebBrowserShortcutsEnabled = false; 


        webBrowser1.ObjectForScripting = this; 


        // Uncomment the following line when you are finished debugging. 

        //webBrowser1.ScriptErrorsSuppressed = true; 

  


        webBrowser1.DocumentText = 


            "

You can also use this technology to deliver an entire object to a web page . In order to achieve it , In your IDispatch Create a method in the implementation , Pass back the objects that your page can use .

Take a look at the example code that uses  ATL Of IDispatch An example of Automation  .

translator's note :IE It also extends the browser's document object model , So that you can extend the object in the script menuArguments Property to access the current window object .

IDocHostUIHandler::GetOptionKeyPath

IDocHostUIHandler::GetOptionKeyPath Is a very powerful tool for customizing browser controls .  Many browser control displays and behavior settings are stored in the registry HKEY_CURRENT_USER Below the key .IDocHostUIHandler::GetOptionKeyPath Give you a chance to override these registry settings for a specific instance of your browser control . It does this by asking you to provide an alternative registry location , The browser control will read the registry settings here .

IDocHostUIHandler::GetOptionKeyPath An implementation of is passed to you to let the browser control read a string of the location set in the registry . Browser controls will be found in HKEY_CURRENT_USER The key below the key .

Example

HRESULT CBrowserHost::GetOptionKeyPath(LPOLESTR *pchKey,

    DWORD dwReserved)

{

    HRESULT hr;

    #define CCHMAX 256

    size_t cchLength;

    if (pchKey)

    {

        WCHAR* szMyKey = L"Software\MyCompany\MyApp";

        hr = StringCchLengthW(szMyKey, CCHMAX, &cchLength);

        //TODO:  Handling errors here .

        *pchKey = (LPOLESTR)CoTaskMemAlloc((cchLength + 1) * sizeof(WCHAR));

        if (*pchKey)

            hr = StringCchCopyW(*pchKey, cchLength + 1, szKey);

        //TODO:  Handling errors here .

        hr = (*pchKey) ? S_OK : E_OUTOFMEMORY;

    }

    else

        hr = E_INVALIDARG;

    return hr;

}

and IDocHostUIHandler::GetHostInfo equally , Make sure to use... For your string  CoTaskMemAlloc Allocate memory .

Telling browser controls where to find your registry settings is actually the first step —— In terms of program operation, it's the second step .  Your program has to be updated before it can be used IDocHostUIHandler::GetOptionKeyPath Tell me where to set a registry key , So that the browser control can read . There are many ways to do this . One way is to execute a registry script when the application is installed . Another way is when the application starts , Do it in code . Here's changing the default font , A setting for size and color .

Example

HRESULT SetSomeKeys()

{

    HKEY hKey = NULL;

    HKEY hKey2 = NULL;

    HKEY hKey3 = NULL;

    DWORD dwDisposition = NULL;

    LONG lResult = NULL;

    #define CBMAX 256

    size_t cbLength;

    RegCreateKeyEx(HKEY_CURRENT_USER, _T("Software\MyCompany\MyApp"),

        NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE,

        NULL, &hKey, &dwDisposition);

    RegCreateKeyEx(hKey, _T("Main"), NULL, NULL, REG_OPTION_NON_VOLATILE,

        KEY_SET_VALUE, NULL, &hKey2, &dwDisposition);

    RegSetValueEx(hKey2, _T("Use_DlgBox_Colors"), NULL, REG_SZ,

        (CONST BYTE*)_T("no"), sizeof(_T("no")));

    RegCloseKey(hKey2);

    RegCreateKeyEx(hKey, _T("Settings"), NULL, NULL, REG_OPTION_NON_VOLATILE,

        KEY_SET_VALUE, NULL, &hKey2, &dwDisposition);

    RegSetValueEx(hKey2, _T("Anchor Color"), NULL, REG_SZ,

        (CONST BYTE*)_T("0,255,255"), sizeof(_T("0,255,255")));

    RegSetValueEx(hKey2, _T("Text Color"), NULL, REG_SZ,

        (CONST BYTE*)_T("255,0,255"), sizeof(_T("255,0,255")));

    RegCloseKey(hKey2);

    RegCreateKeyEx(hKey, _T("International\Scripts"), NULL, NULL,

        REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL,

        &hKey2, &dwDisposition);

    BYTE bDefaultScript = 0x3;

    RegSetValueEx(hKey2, _T("Default_Script"), NULL, REG_BINARY,

        &bDefaultScript, sizeof(bDefaultScript));

    RegCreateKeyEx(hKey2, _T("3"), NULL, NULL, REG_OPTION_NON_VOLATILE,

        KEY_SET_VALUE, NULL, &hKey3, &dwDisposition);

    BYTE bSize = 0x4; // Value from 0 - 4. 2 is medium.

    TCHAR* szFontName = _T("Comic Sans MS");

    TCHAR* szFixedFontName = _T("Courier");

    HRESULT hr = StringCbLength(szFontName, CBMAX, &cbLength);

    //TODO:  Handling errors here .

    RegSetValueEx(hKey3, _T("IEPropFontName"), NULL, REG_SZ,

        (CONST BYTE*)szFontName, cbLength + sizeof(TCHAR));

    hr = StringCbLength(szFixedFontName, CBMAX, &cbLength);

    //TODO:  Handling errors here .

    RegSetValueEx(hKey3, _T("IEFixedFontName"), NULL, REG_SZ,

        (CONST BYTE*)szFixedFontName, cbLength + sizeof(TCHAR));

    RegSetValueEx(hKey3, _T("IEFontSize"), NULL, REG_BINARY, &bSize, sizeof(bSize));

    RegCloseKey(hKey3);

    RegCloseKey(hKey2);

    RegCloseKey(hKey);

    return S_OK;

}

IDocHostUIHandler2

IDocHostUIHandler2  There is only one way ,IDocHostUIHandler2::GetOverrideKeyPath. It runs very much like IDocHostUIHandler::GetOptionKeyPath A function of . It indicates where you modify the registry settings used by the integrated browser from the default registry settings .IDocHostUIHandler2::GetOverrideKeyPath  An implementation of would look very similar to IDocHostUIHandler::GetOptionKeyPath An implementation of .

GetOptionKeyPath  and  GetOverrideKeyPath  Comparison

You may not see it IDocHostUIHandler::GetOptionKeyPath and IDocHostUIHandler2::GetOverrideKeyPath Any difference between them . The difference between them is subtle ,  But it's important . If you achieve  IDocHostUIHandler::GetOptionKeyPath, Your browser control instance will ignore any IE User settings for . These settings are stored in the registry HKEY_CURRENT_USER/Software/Microsoft/Internet Explorer below . If you achieve IDocHostUIHandler2::GetOverrideKeyPath, Your browser control instance will incorporate any user settings — Font settings , Menu extension , And so on —— Into its display and behavior .

For example, in the IDocHostUIHandler::GetOptionKeyPath and IDocHostUIHandler2::GetOverrideKeyPath Differences between , Let's look at it again IDocHostUIHandler::ShowContextMenu Sample code for that section . Remember this line :

spCT->Exec(&CGID_ShellDocView, SHDVID_ADDMENUEXTENSIONS, 0, &var1, &var2);

If you have IDocHostUIHandler::GetOptionKeyPath, Because the menu extension information is stored in the current user's registry information , So this line doesn't add any custom items to the shortcut menu . If you have IDocHostUIHandler2::GetOverrideKeyPath,  This line will be added to the HKEY_CURRENT_USER/Software/Microsoft/Internet Explorer/MenuExt Any current user-defined menu extension of the face definition ,  Unless you explicitly provide an empty or alternative MenuExt key .

Control navigation

You may want to know where IDocHostUIHandler Why not mention it in that section  IDocHostUIHandler::TranslateUrl, As a way to do this when you want to control page navigation . The reason is that this method is not the most common technology to control navigation .  Unless you integrate directly MSHTML, This method will not have the effect of controlling navigation . As a substitute , By implementing IDispatch::Invoke, Handle DISPID_BEFORENAVIGATE2, You can control the navigation . for example , The following code avoids navigating to a particular URL , If the user tries to do this , Will be displayed  " No navigation allowed "  Error page .

Example

case DISPID_BEFORENAVIGATE2:

{

    CComBSTR url = ((*pDispParams).rgvarg)[5].pvarVal->bstrVal;

    if (url == "http://www.adatum.com" || url == "http://www.adatum.com/")

    {

        CComPtr

        CComPtr

        spDisp->QueryInterface(IID_IWebBrowser2, (void**)&spBrowser);

        spBrowser->Stop();

        CComBSTR newURL = "L"res://webhost.exe/nonavigate.htm";

        spBrowser->Navigate(newURL, NULL, NULL, NULL, NULL);

        ((*pDispParams).rgvarg)[0].boolVal = TRUE;

    }

    break;

}

IDocHostShowUI

This interface gives you control over the information dialog box and help displayed by the browser control . It's working mechanism and IDocHostUIHandler and IDocHostUIHandler2 equally , You realize it , So before the browser control displays any of its own information or help  , Can call your IDocHostShowUI Methods . This gives you a chance to prevent the browser control from displaying anything , And it allows you to display your own custom information or help instead . IDocHostShowUI There are two ways ,IDocHostShowUI::ShowMessage and IDocHostShowUI::ShowHelp.

IDocHostShowUI::ShowMessage

return  S_OK Disable the browser control's information dialog . Any other return value , image S_FALSE or E_NOTIMPL, Allow the browser control to display its information dialog .

One of the good things you can do with this method is to customize the Infobox title for your application , replace  "Microsoft Internet Explorer" . You can compare lpstrCaption And stored in Shdoclc.dll Medium IE Use the string resource to complete it . its ID yes IDS_MESSAGE_BOX_TITLE, Values are 2213. The following sample code demonstrates what you might need to do .

Example

HRESULT CBrowserHost::ShowMessage(HWND hwnd,

    LPOLESTR lpstrText,

    LPOLESTR lpstrCaption,

    DWORD dwType,

    LPOLESTR lpstrHelpFile,

    DWORD dwHelpContext,

    LRESULT *plResult)

{

    USES_CONVERSION;

    TCHAR pBuffer[50];

    //  Window title "Microsoft Internet Explorer" Resource ID for

    #define IDS_MESSAGE_BOX_TITLE 2213

    // load Shdoclc.dll  and IE Message box title string

    HINSTANCE hinstSHDOCLC = LoadLibrary(TEXT("SHDOCLC.DLL"));

    if (hinstSHDOCLC == NULL)

    {

        //  Error loading module  --  Fail as safely as possible

        return;

    }

    LoadString(hinstSHDOCLC, IDS_MESSAGE_BOX_TITLE, pBuffer, 50);

    //  Compare IE Message box title string and lpstrCaption

    //  If the same , Replace with custom title

    if (_tcscmp(OLE2T(lpstrCaption), pBuffer) == 0)

        lpstrCaption = L"Custom Caption";

    //  Create your own message box and display

        *plResult = MessageBox(OLE2T(lpstrText), OLE2T(lpstrCaption), dwType);

    // uninstall Shdoclc.dll And back to

    FreeLibrary(hinstSHDOCLC);

    return S_OK;

}

Safety warning : Incorrect use LoadLibrary Can load the wrong DLL (DLL) To threaten the security of your application . About how to use Microsoft correctly Windows Different versions of DLL Information about , reference  LoadLibrary Documents .

IDocHostShowUI::ShowHelp

It's a way to do it IE Called when help needs to be displayed , For example, when  F1  When the key is pressed , And the way it works is different IDocHostShowUI::ShowMessage similar . return S_OK Cover IE With the help of the , Or something else HRESULT It's worth letting IE Carry out your own help .

Control download and execution

Browser control gives you its download , Show control of setup and execution .  In order to get these controls , You implement your host's IDispatch Interface , Make it handle DISPID_AMBIENT_DLCONTROL. When the browser control is instantiated , It will take this one ID Call your IDispatch::Invoke. take pvarResult Set to a combination of one bit of the following identifier and , Indicate your configuration .

· DLCTL_DLIMAGES , DLCTL_VIDEOS  and  DLCTL_BGSOUNDS:  If these signs are set , Images , Video and background music will be downloaded from the server and displayed or played , Otherwise it will not be downloaded and displayed .

· DLCTL_NO_SCRIPTS  and  DLCTL_NO_JAVA:  Scripts and Java The applet will not be run .

· DLCTL_NO_DLACTIVEXCTLS  and  DLCTL_NO_RUNACTIVEXCTLS: ActiveX  Control will not be downloaded or run .

· DLCTL_DOWNLOADONLY:  The page will only be downloaded , No display .

· DLCTL_NO_FRAMEDOWNLOAD: Browser controls will download and parse frameset pages , But it doesn't download and parse the individual frameworks in the frameset .

· DLCTL_RESYNCHRONIZE  and  DLCTL_PRAGMA_NO_CACHE:  These signs lead to Internet Buffer refresh . adopt  DLCTL_RESYNCHRONIZE, The server will be asked to update the status . If the server indicates that the cache information is up-to-date , Will use   Cache file . adopt DLCTL_PRAGMA_NO_CACHE, Regardless of the update status of the file , Files will be downloaded from the server again .

· DLCTL_NO_BEHAVIORS:  Behavior is not downloaded and is disabled in the file .

· DLCTL_NO_METACHARSET_HTML:  Ignore in META The character set specified in the element .

· DLCTL_URL_ENCODING_DISABLE_UTF8  and  DLCTL_URL_ENCODING_ENABLE_UTF8:  The function of these signs is similar to IDocHostUIHandler::GetHostInfo Used in DOCHOSTUIFLAG_URL_ENCODING_DISABLE_UTF8 and DOCHOSTUIFLAG_URL_ENCODING_ENABLE_UTF8 sign . The difference is that only when the browser control is initialized ,DOCHOSTUIFLAG The logo will be checked . The download flag of the environment feature change here is checked every time the browser control needs to run a download .

· DLCTL_NO_CLIENTPULL:  Do not run the client relocation page operation ( translator's note : for example   Default behavior of ).

· DLCTL_SILENT:  There is no user interface display during download .

· DLCTL_FORCEOFFLINE:  Browser controls always operate in offline mode .

· DLCTL_OFFLINEIFNOTCONNECTED  and  DLCTL_OFFLINE:  The signs are the same . If you don't connect to the Internet , Browser controls will operate in offline mode .

DISPID_AMBIENT_DLCONTROL And the value of the flag is in the mshtmdid.h Defined .

first , When the IDispatch::Invoke At the beginning of the call , pvarResult The parameter points to VARIANT yes VT_EMPTY type .  You have to set it to... For any valid settings VT_I4 type . You can VARIANT Of lVal Store flag values in members .

Most flag values have a negative effect , in other words , They avoid normal behavior . for instance , If you don't customize browser control behavior , So the script is usually executed .  But if you set DLCTL_NOSCRIPTS  sign , The script will not run in the instance under control . However , Three signs — DLCTL_DLIMAGES , DLCTL_VIDEOS  and  DLCTL_BGSOUNDS The opposite is true . You have to set up all the signs , Make the browser control execute about the image with its default behavior , Video and sound processing .

The following example code enables a browser control instance to download and display images and videos , But don't deal with background music , because DLCTL_BGSOUNDS It's not explicitly set . Script running on the page displayed by the browser control is disabled .

STDMETHODIMP CAtlBrCon::Invoke(DISPID dispidMember, REFIID riid,

    LCID lcid, WORD wFlags,

    DISPPARAMS* pDispParams,

    VARIANT* pvarResult,

    EXCEPINFO* pExcepInfo,

    UINT* puArgErr)

{

    switch (dispidMember)

    {

        case DISPID_AMBIENT_DLCONTROL:

            pvarResult->vt = VT_I4;

            pvarResult->lVal = DLCTL_DLIMAGES | DLCTL_VIDEOS | DLCTL_NO_SCRIPTS;

            break;

        default:

            return DISP_E_MEMBERNOTFOUND;

    }

    return S_OK;

}

IHostDialogHelper

IHostDialogHelper It's an interface where you can create dialog boxes according to your hobbies . This interface has a method ,IHostDialogHelper::ShowHTMLDialog. This method provides functions like ShowHTMLDialog General service , But it's a little easier to use .

In order to use IHostDialogHelper, You create dialog helper objects from scratch . Here is what you use CoCreateInstance Create it in a different way . Interface and ID stay  mshtmhst.h  Is defined in .

Example

IHostDialogHelper* pHDH;

IMoniker* pUrlMoniker;

BSTR bstrOptions = SysAllocString(L"dialogHeight:30;dialogWidth:40");

BSTR bstrPath = SysAllocString(L"c:\dialog.htm");

CreateURLMoniker(NULL, bstrPath, &pUrlMoniker);

//  Create dialog helper objects

CoCreateInstance(CLSID_HostDialogHelper,

    NULL,

    CLSCTX_INPROC,

    IID_IHostDialogHelper,

    (void**)&pHDH);

// call ShowHTMLDialog  Create dialog

pHDH->ShowHTMLDialog(NULL,

    pUrlMoniker,

    NULL,

    bstrOptions,

    NULL,

    NULL);

// Release resources

SysFreeString(bstrPath);

SysFreeString(bstrOptions);

pUrlMoniker->Release();

pHDH->Release();

translator's note : If you want to use dialog boxes to get user input , You may need to pass two parameters to ShowHTMLDialog. About ShowHTMLDialog Parameter description , See Platform SDK file .ShowHTMLDialog and ShowHTMLDialogEx  It seems to have been MSHTML.DLL Two derived functions , Microsoft encapsulates it as an interface , Maybe preparing for future compatibility .

Control new windows

An important way to control browser controls is to control navigation . You've seen before how to IDispatch::Invoke To intercept DISPID_BEFORENAVIGATE2 To control the navigation position of your browser controls . Another important aspect of navigation is to control how navigation happens ,  Especially when opening a new window . Let's give an example ,  The user right clicks on a link , choice  " Open in new window "  Or a page containing scripts like this :

window.open("www.msn.com")

By default , The browser control handles this line of code by opening IE To display the web page . This may be exactly what your application needs , But maybe not . Maybe you need to open all links in the current browser control instance , Or you will have a new instance of the browser control under your control —— With your user interface and your logo —— Open the link .

You can be in your IDispatch Intercept an event in the implementation ——DWebBrowserEvents2::NewWindow2—— To control it . Your control needs to be connected to DWebBrowserEvents2 To intercept this event .

You're connected DWebBrowserEvents2 after , Realize your IDispatch::Invoke To deal with  DISPID_NEWWINDOW2. For DISPID_NEWWINDOW2 Of IDispatch::Invoke Function call , Array pDispParams Contains two parameters . first , The serial number is zero ,  Is a Boolean value , Tell the browser control whether to cancel the new window . By default, it is false , And it will open a new window . If you want to cancel the creation of a new window completely ,  Set the flag to the true value .

The parameter with sequence number one is a IDispatch Pointer to interface . You can set this parameter to the browser control you have created IDispatch. When you send back such a message IDispatch after ,MSHTML Will use the control you give to open the link .

translator's note :MFC Medium DHTML Class and class wizard support this event by default . If you need more information , See MSJ1998 year 7 Month's article Keeping an Eye on Your Browser by Monitoring Internet Explorer 4.0 Events, as well as   Microsoft Knowledge Base article  Q184876 HOWTO: Use the WebBrowser Control NewWindow2 Event

Displays a positive number dialog box

IE6 Or later , You can browse through a legitimate Secure Hypertext Transfer Protocol (HTTPS) The Certificate dialog box will be displayed when you visit the site . This is the same as user click IE The lock icon in has the same effect . You can go through  DWebBrowserEvents2::SetSecureLockIcon Events to display your own icons .

#define SHDVID_SSLSTATUS 33

IOleCommandTarget *pct;

if (SUCCEEDED(pWebBrowser2->QueryInterface(IID_IOleCommandTarget, (void **) &pct)))

{

   pct->Exec(&CGID_ShellDocView, SHDVID_SSLSTATUS, 0, NULL, NULL);

   pct->Release();

}

Information bar

Windows XP SP2  Medium Internet Explorer 6  A new secure user interface element has been introduced , It's called the information bar . When a particular operation is blocked , The information bar shows the user a user interface element . Special , It will be displayed when the following operations are blocked .

·  Pop up initialization ( See   Pop up killer )

· 

·  File download  (see  Restrictions on file download )

· 

·  install ActiveX  Control (see ActiveX  The limitation of )

· 

· ActiveX The reason for the control security prompt is that the user's security settings or the control is not marked as script safe .

· 

·  File extensions and Multipurpose Internet mail extension types (MIME) Inconsistent ( See  MIME  Handle )

· 

·  Content of network protocol lock ( See   agreement )

· 

The information bar is Windows XP SP2  Medium Internet Explorer 6 One of the security features introduced . Like any other security feature control , It can be controlled by a registry key :(FEATURE_SECURITYBAND).  By default IE(iexplorer.exe)  and Windows  Explorer (explorer.exe)  Under the control of this security feature . The registry key and enable process are shown below :

HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)

SOFTWARE

Microsoft

Internet Explorer

Main

FeatureControl

FEATURE_SECURITYBAND

iexplorer.exe= 0x00000001

explorer.exe= 0x00000001

process name.exe=0x00000001

This FEATURE_SECURITYBAND  Control effect of safety characteristics IE Display information bar , The information bar prompts the user when an operation is blocked . It doesn't control the blocking process of the operation .

A program integrating browser controls can enable the information bar by adding its processes to the registry key . This can be done by calling CoInternetSetFeatureEnabled Function to execute at run time . If an application is not under the control of this security feature , So the behavior of browser controls and Internet Explorer 6 SP1b The same as in China .

There is no way to access this feature through scripts .

stay FEATURE_SECURITYBAND And related security features under the control of the application can use the information bar application programming interface (API) In one URL  operation Customize the user interface when disabled . A lot of new things have been introduced to the information bar OLECMDID command . The first three belong to CGID_DocHostCommandHandler Group . Host applications should be in their IDocHostUIHandler Implementation in the same object IOleCommandTarget , To accept IOleCommandTarget::Exec call .

· OLECMDID_PAGEACTIONBLOCKED

· 

· OLECMDID_PAGEACTIONUIQUERY

· 

· OLECMDID_FOCUSVIEWCONTROLS

· 

The host application can use the following two new OLECMDID  Command to execute the IOleCommandTarget::Exec call .

· OLECMDID_FOCUSVIEWCONTROLSQUERY

· 

· OLECMDID_SHOWPAGEACTIONMENU

· 

This example uses IWebBrowser2::ExecWB  To execute OLECMDID_SHOWPAGEACTIONMENU  command .

   POINT pt = { 0 };

   GetCursorPos(&pt);

   CComVariant varHwnd((LONG)hwnd);

   CComVariant varX(pt.x);

   CComVariant varY(pt.y);

   SAFEARRAY* psa = SafeArrayCreateVector(VT_VARIANT, 0, 3);

   LONG lIndex = 0;

   SafeArrayPutElement(psa, &lIndex, &varHwnd);

   lIndex++;

   SafeArrayPutElement(psa, &lIndex, &varX);

   lIndex++;

   SafeArrayPutElement(psa, &lIndex, &varY);

   CComVariant varArgIn;

   V_VT(&varArgIn) = VT_ARRAY | VT_I4;

   V_ARRAY(&varArgIn) = psa;

   pBrowser->ExecWB(OLECMDID_SHOWPAGEACTIONMENU, (OLECMDEXECOPT)dwPageActionFlags, &varArgIn, NULL);

in addition , Applications can be implemented IInternetSecurityManager To override the default security zone settings , See Create a custom URL Safety manager For more information .

Conclusion

You have a lot of technology now , You can customize browser controls according to your processing . This article is by no means without omission , But I hope you can now discover beyond this article . Check IE Registry settings that you can use IDocHostUIHandler::GetOptionKeyPath or IDocHostUIHandler2::GetOverrideKeyPath Modified information . Remember that many registry settings depend on each other . You may have to do some experiments to find out how well registry settings can be customized ; If you need to control the drag and drop behavior of browser controls , You can also have a look at IDocHostUIHandler::GetDropTarget.

C# WinForm WebBrowser ( 5、 ... and )  Annoying questions  

WebBrowse  Edit mode   A few annoying questions in English :

1、 When setting DocumentText Property value will always pop up a “ Hateful save dialog ”

The better strategies I know now are :
1) Set up two DocumentText Use between attribute values webBrowser1.Document.OpenNew(true) Method , But this approach raises some problems . The details are as follows .
2) Set up DocumentText Change edit mode to browse mode before properties , After setting, change the browse mode to edit mode .


2、 monitor Html Changes in content .

monitor  WebBrowser  Control content change


3、WebBrowse Of Mouse event .

WebBrowse There is no such thing as Mouse Related events , But we can use WebBrowse Medium Body Element to simulate some simple related events .

// stay WinForm Register in Web event
// hypothesis HTML The source code is as follows :

 
// WinForm Register in Web event
HtmlDocument htmlDoc = webBrowser.Document; 
HtmlElement btnElement = htmlDoc.All["btnClose"]; 
if (btnElement != null) 

    btnElement.click += new HtmlElementEventHandler(HtmlBtnClose_Click); 
}

WebBrowse For more practical methods in, see :C#WinForm WebBrowser ( Two )  Summary of practical methods


4、webBrowser1.Document.OpenNew(true) Of Bug

Related links :
1) Tracking leads to  WebBrowser Control   In edit mode  Ctrl + Z  The cause of the failure  【 Great Xia, please , Is this Microsoft's Bug Well ?】

Tracking leads to  WebBrowser Control   In edit mode  Ctrl + Z  The cause of the failure  【 Great Xia, please , Is this Microsoft's Bug Well ?】 


Lead to Ctrl  + Z The causes of failure are as follows 2 Caused by point chain :

1、 In order to solve  WebBrowser  Pop up when control navigates “ Save Dialog ”, Used  this.webBrowser.Document.OpenNew(true); //  prevent   The save dialog box pops up ,  This method indicates that a new text change will open in a new window .

2、  By reason 1 Lead to  webBrowser  Invalid edit mode for control ,  On the surface, it looks like it can be edited , But in fact, editing is no longer supported inside the new window .

notes : This is where WebBrowser The particularity of control , It is nested by three layers of controls , The outer two layers are probably responsible for the container 、  And   Responding to user actions ,  And the innermost layer is carrying capacity HTML Mark , And show it through the rendering engine HTML Content . Use black box test We can infer that , When using webBrowser.Document.OpenNew(true);   When the method is used , The innermost control should be a new instance ,  On the surface, it looks like it can be edited , But in fact, the new windows inside no longer support editing , And that led to Ctrl + Z The failure of !

The test code is as follows :

public partial class FrmTest : Form
{
//  There's a... on the interface WebBrowser  and  4 individual Button

private string strUrl = "http://www.cnblogs.com/08shiyan";

public FrmTest()
{
InitializeComponent();
}

/// 
public void EditMode()
{
if (this.webBrowser1.Document != null)
{
mshtml.IHTMLDocument2 doc = this.webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
doc.designMode = "on";
}
}

/// 
public void BrowseMode()
{
if (this.webBrowser1.Document != null)
{
mshtml.IHTMLDocument2 doc = this.webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
doc.designMode = "off";
}
}

//  Please make sure that this button is the first time that the application has been started
private void button1_Click(object sender, EventArgs e)
{
this.webBrowser1.DocumentText = string.Empty;
this.webBrowser1.Document.Write(string.Format("", this.strUrl));
this.EditMode();

this.webBrowser1.Document.OpenNew(true);
this.webBrowser1.Document.Write(string.Format("", this.strUrl));

//  Note that this time Ctrl + Z  The undo operation will be invalid
}

//  Please make sure that this button is the first time that the application has been started
private void button2_Click(object sender, EventArgs e)
{
this.webBrowser1.DocumentText = string.Empty;
this.webBrowser1.Document.Write(string.Format("", this.strUrl));
this.EditMode();

this.webBrowser1.Document.OpenNew(true);
this.webBrowser1.Document.Write(string.Format("", this.strUrl));

this.EditMode(); //  And button1 The difference is to enable edit mode again  //  Note that this time Ctrl + Z  The undo operation will also fail
}

//  Please make sure that this button is the first time that the application has been started
private void button3_Click(object sender, EventArgs e)
{
this.webBrowser1.DocumentText = string.Empty;
this.webBrowser1.Document.Write(string.Format("", this.strUrl));
this.EditMode();

this.webBrowser1.Document.OpenNew(true);
this.webBrowser1.Document.Write(string.Format("", this.strUrl));

this.BrowseMode(); //  And button2  Is the difference between the   Turn off edit mode first , Re enable edit mode
this.EditMode();

//  here  Ctrl + Z  have access to
}

//  Restart application
private void button4_Click(object sender, EventArgs e)
{
Application.Restart();
}

}

According to the above conclusion :
stay “ Edit mode ” Next : this.webBrowser.Document.OpenNew(true);  Method opens a new “ Internal window ”, And in the new window “ Edit mode ” Problems arise , Lead to Ctrl + Z ,Ctrl +Y Operation failure .  here   Need to close first  “ Edit mode ”  Then open it again “ Edit mode ” Ctrl + Z, Ctrl +Y  For normal use .

Ask for proof ...

original   Reprint please indicate the source : http://www.cnblogs.com/08shiyan

2)http://topic.csdn.net/u/20110318/14/e3744686-3dae-4152-a1d8-c0011e8f355c.html

Please bring the original link to reprint ,thank
Similar articles

2021-06-04

2021-06-04

2021-06-06

2021-06-27

2021-06-29