.NET - Using CefSharp

using System;
using System.Windows.Forms;
using CefSharp.WinForms;
using CefSharp;

namespace CefTest
{
    public class MyObject
    {
        public void showMessage(string msg)
        {
            MessageBox.Show(msg, "Windows Message");
        }

        public void openCalc()
        {
            System.Diagnostics.Process.Start("calc.exe");
        }

        public override string ToString()
        {
            return "MyObject (C#)";
        }
    }

    public partial class MainForm : Form
    {
        ChromiumWebBrowser _browser;

        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            Cef.Initialize(settings);
            _browser = new ChromiumWebBrowser("https://developer.mozilla.org/zh-CN/docs/Web/Guide");
            _browser.Dock = DockStyle.Fill;
            this.panel1.Controls.Add(_browser);

            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.FileAccessFromFileUrls = CefState.Enabled;
            browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
            _browser.BrowserSettings = browserSettings;

            CefSharpSettings.LegacyJavascriptBindingEnabled = true;
            _browser.RegisterJsObject("myObject", new MyObject());
        }

        public MainForm()
        {
            InitializeComponent();
            InitializeChromium();
        }

        private void showDevToolToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _browser.ShowDevTools();
        }
    }
}
  • 运行程序,打开 DevTool 的 Console,测试 Cef 对象:
> myObject
{showMessage: ƒ, getComputerName: ƒ, toString: ƒ, equals: ƒ, getHashCode: ƒ}

> myObject.toString()
"MyObject (C#)"

> myObject.getComputerName()
"WINA1080"