CefSharp ——js呼叫c#方法

westwolf發表於2021-09-09

摘要

有時我們在winform中嵌入瀏覽器,需要在頁面上讀取電腦上的一些資訊,這個時候就需要用到CefSharp的RegisterJsObject進行註冊方法然後供js進行呼叫了。

一個例子

我們在winform中嵌入的頁面中,顯示電腦的資訊,電腦資訊透過winform進行讀取,js呼叫獲取電腦資訊的方法,並將最終結果以json字串的形式傳遞到js端,js獲取到這些資訊並在頁面上進行顯示。

定義一個專門處理js回撥的類


    /// 
    /// js c#回撥類
    /// 
    class ScriptCallbackManager
    {
        /// 
        /// 查詢電腦資訊
        /// 
        /// 
        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類為獲取電腦資訊的操作類


    /// 
    /// 電腦資訊類
    /// 
    public class Computer
    {
        /// 
        /// 查詢cpu的id
        /// 
        /// 
        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;
                }
            }
        }
        /// 
        /// 網路卡
        /// 
        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;
                }
            }
        }
        /// 
        /// 獲取序列號,製造商,型號
        /// 
        public Tuple SerialNumber_Manufacturer_Product
        {
            get
            {
                try
                {
                    Tuple tuple = null; new Tuple(string.Empty, 
string.Empty, string.Empty);
                    ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_baseboard");


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

                    return null;
                }
            }
        }
        /// 
        /// 計算機名稱
        /// 
        public string HostName
        {
            get
            {
                return System.Net.Dns.GetHostName();
            }
        }
    }

嵌入的頁面


html>



    
    
    
         

    單擊按鈕,在頁面上顯示當前電腦資訊

    窗體程式碼

        /// 
        /// 主窗體
        /// 
        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);
                
            }
            /// 
            /// 載入頁面
            /// 
            /// 
            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的特點,可以在電腦端,移動端訪問,而不是每個終端都寫程式碼。

    來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4662/viewspace-2800845/,如需轉載,請註明出處,否則將追究法律責任。

    相關文章