简体   繁体   中英

How to properly initialize CefSharp web browser

I am using the CefSharp web browser in my project. But when I switch between two WinForms I got this exception.

System.Exception: 'CEF can only be initialized once per process. This is a limitation of the underlying CEF/Chromium framework. You can change many (not all) settings at runtime through RequestContext.SetPreference. See https://github.com/cefsharp/CefSharp/wiki/General-Usage#request-context-browser-isolation Use Cef.IsInitialized to guard against this exception. If you are seeing this unexpectedly then you are likely calling Cef.Initialize after you've created an instance of ChromiumWebBrowser, it must be before the first instance is created.'

Here is the code.

public ChromiumWebBrowser browser;


    public void InitBrowser()
    {
        Cef.Initialize(new CefSettings());
        browser = new ChromiumWebBrowser(Settings.Default.SetLink);
        this.GpBrwsr.Controls.Add(browser);
        browser.Dock = DockStyle.Fill;
    }
    public Form3()
    {
    
        InitBrowser();
    }

    private void browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
    {
        if (e.IsLoading == false)
        {
            browser.ExecuteScriptAsync("alert('All Resources Have Loaded');");
        }
    }

And here is how i am switching between forms.

LoginToSettings Login = new LoginToSettings();
Login.Show();
this.Hide();

异常图像

My question is how do I initialize it so I don't stumble upon this exception? I also tried "Form Minimization" Option instead of "Form Hiding" But still the same issue.

I have used this link for using CefSharp browser. Code Source for CefSharp

For future ppl who come by here:

If you do want to call Cef.Initialize(....); (of course with some args such as CefSettings obj etc..)

You must call is BEFORE any creation of a new ChromiumWebBrowser() as a creation of the browser will infact Initialize Cef with the default settings, And as you may gusse it will rise an error once you will try call Initialize again as it can only be initialized once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM