继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

CefSharp ——js调用c#方法

冉冉说
关注TA
已关注
手记 324
粉丝 42
获赞 194

摘要

有时我们在winform中嵌入浏览器,需要在页面上读取电脑上的一些信息,这个时候就需要用到CefSharp的RegisterJsObject进行注册方法然后供js进行调用了。

一个例子

我们在winform中嵌入的页面中,显示电脑的信息,电脑信息通过winform进行读取,js调用获取电脑信息的方法,并将最终结果以json字符串的形式传递到js端,js获取到这些信息并在页面上进行显示。

定义一个专门处理js回调的类


    /// <summary>
    /// js c#回调类
    /// </summary>
    class ScriptCallbackManager
    {
        /// <summary>
        /// 查找电脑信息
        /// </summary>
        /// <param name="javascriptCallback"></param>
        public void FindComputerInfo(IJavascriptCallback javascriptCallback)
        {

            Task.Factory.StartNew(async () =>
            {

                using (javascriptCallback)
                {
                    Computer computer = new Computer();
                    string response = JsonConvert.SerializeObject(new
                    {
                        cpu_id = computer.CPU_Id,
                        disk_id = computer.Disk_Id,
                        host_name = computer.HostName,
                        networkcard = computer.NetworkCard,
                        serialNumber = computer.SerialNumber_Manufacturer_Product.Item1,
                        manufacturer = computer.SerialNumber_Manufacturer_Product.Item2,
                        product = computer.SerialNumber_Manufacturer_Product.Item3,
                    });
                    await javascriptCallback.ExecuteAsync(response);
                }
            });

        }


    }

其中computer类为获取电脑信息的操作类


    /// <summary>
    /// 电脑信息类
    /// </summary>
    public class Computer
    {
        /// <summary>
        /// 查找cpu的id
        /// </summary>
        /// <returns></returns>
        public string CPU_Id
        {
            get
            {
                try
                {
                    string str = string.Empty;
                    ManagementClass mcCPU = new ManagementClass("win32_Processor");
                    ManagementObjectCollection mocCPU = mcCPU.GetInstances();
                    foreach (ManagementObject m in mocCPU)
                    {
                        str = m["Processorid"].ToString().Trim().Substring(0, 8);
                        break;
                    }
                    return str;
                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }
        }
        public string Disk_Id
        {
            get
            {
                try
                {
                    string hdId = string.Empty;
                    ManagementClass hardDisk = new ManagementClass("win32_DiskDrive");
                    ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
                    foreach (ManagementObject m in hardDiskC)
                    {
                        hdId = m.Properties["Model"].Value.ToString();//WDC WD800BB-56JKC0
                        break;
                    }
                    return hdId;
                }
                catch (Exception)
                {

                    return string.Empty;
                }
            }
        }
        /// <summary>
        /// 网卡
        /// </summary>
        public string NetworkCard
        {
            get
            {
                try
                {
                    string MoAddress = string.Empty;
                    ManagementClass networkAdapter = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection adapterC = networkAdapter.GetInstances();
                    foreach (ManagementObject m in adapterC)
                    {
                        if ((bool)m["IPEnabled"] == true)
                        {
                            MoAddress = m["MacAddress"].ToString().Trim();
                            m.Dispose();
                        }
                    }
                    return MoAddress;
                }
                catch
                {
                    return string.Empty;
                }
            }
        }
        /// <summary>
        /// 获取序列号,制造商,型号
        /// </summary>
        public Tuple<string, string, string> SerialNumber_Manufacturer_Product
        {
            get
            {
                try
                {
                    Tuple<string, string, string> tuple = null; new Tuple<string, string, string>(string.Empty, 
string.Empty, string.Empty);
                    ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_baseboard");


                    foreach (ManagementObject m in mos.Get())
                    {
                        tuple = new Tuple<string, string, string>(m["SerialNumber"].ToString(), m["Manufacturer"].ToString(),
 m["Product"].ToString());
                    }
                    return tuple;
                }
                catch (Exception)
                {

                    return null;
                }
            }
        }
        /// <summary>
        /// 计算机名称
        /// </summary>
        public string HostName
        {
            get
            {
                return System.Net.Dns.GetHostName();
            }
        }
    }

嵌入的页面


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/jquery.min.js"></script>
    <script>

        //设置电脑信息
        function callback(data) {
            data = JSON.parse(data);
            $("#msg").html('');
            $("#msg")
            .append($("<li>cpu_id:" + data.cpu_id + "</li>"))
            .append($("<li>disk_id:" + data.disk_id + "</li>"))
            .append($("<li>host_name:" + data.host_name + "</li>"))
            .append($("<li>networkcard:" + data.networkcard + "</li>"))
            .append($("<li>serialNumber:" + data.serialNumber + "</li>"))
            .append($("<li>manufacturer:" + data.manufacturer + "</li>"))
            .append($("<li>product:" + data.product + "</li>"));
        };
        function findComputerInfo() {
            //调用后台C#FindComputerInfo,返回结果回调方法callback
            googleBrower.FindComputerInfo(callback);
        };
    </script>
</head>
<body>
    <button onclick="findComputerInfo()">获取电脑信息</button>
    <ul id="msg"></ul>
</body>
</html>

单击按钮,在页面上显示当前电脑信息

窗体代码

    /// <summary>
    /// 主窗体
    /// </summary>
    public partial class MainFrm : Form
    {
        private CefSharp.CefSettings _settings;
        CefSharp.WinForms.ChromiumWebBrowser _webView;
        public MainFrm()
        {
            InitializeComponent();
            _settings = new CefSharp.CefSettings();
            CefSharp.Cef.Initialize(_settings);
            this.FormClosed += MainFrm_FormClosed;
        }

        void MainFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_webView != null)
            {
                _webView.Dispose();
            }
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            string url = "file:///E:/xxx/bin/x64/Debug/lenovo/test.html";
            LoadPage(url);
            
        }
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="url"></param>
        private void LoadPage(string url)
        {
            if (_webView == null)
            {
                _webView = new CefSharp.WinForms.ChromiumWebBrowser(url);
                _webView.Dock = DockStyle.Fill;
                _webView.LifeSpanHandler = new OpenPageSelf();
                _webView.RegisterJsObject("googleBrower", new ScriptCallbackManager(), 
new CefSharp.BindingOptions { CamelCaseJavascriptNames = false });
                this.Controls.Add(_webView);
            }
            else
            {
                _webView.Load(url);
            }
        }
    }

测试

总结

通过在winform嵌入浏览器,可以很方便处理h5页面的展示,不用再使用winform再开发一个客户端的程序,完全可以嵌入要开发的h5应用,这样完全应用了h5的特点,可以在电脑端,移动端访问,而不是每个终端都写代码。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP