C # how to embed Winform into Google Chrome and JS,

Source: Internet
Author: User

C # how to embed Winform into Google Chrome and JS,

First, we need to build the environment

Create a winform project GoogleChromeTest

Manage NuGet packages, search for cef, and install CefSharp. WinForms

The X86 runtime environment is selected here, so you need to add reference to X86. (If you need X64 development, you can select X64. The reference later must also be changed to X64)

Add reference

There is a packages file in the project folder.

Add

Packages \ CefSharp. WinForms.57.0.0 \ CefSharp \ x86 \ CefSharp. WinForms. dll

Packages \ CefSharp. Common.57.0.0 \ CefSharp \ x86 \ CefSharp. BrowserSubprocess. Core. dll

Packages \ CefSharp. Common.57.0.0 \ CefSharp \ x86 \ CefSharp. Core. dll

Packages \ CefSharp. Common.57.0.0 \ CefSharp \ x86 \ CefSharp. dll

Generate the project and restart.

Now we are writing code.

Add two buttons, one textBox

The main interface code is as follows:

Using CefSharp. winForms; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. threading. tasks; using System. windows. forms; namespace GoogleChromeTest {public partial class Form1: Form {////// Chromium browser instance ///ChromiumWebBrowser WebBrowser; public Form1 () {InitializeComponent (); // set var setting = new CefSharp. cefSettings (); setting. locale = "zh-CN"; setting. cachePath = "CHBrowser/BrowserCache"; // cache path setting. acceptLanguageList = "zh-CN, zh; q = 0.8"; // browser engine language setting. localesDirPath = "CHBrowser/localeDir"; // log setting. logFile = "CHBrowser/LogData"; // log file setting. persistSessionCookies = true; // setting. userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"; // browser kernel setting. userDataPath = "CHBrowser/userData"; // Personal Data // initialize CefSharp. cef. initialize (setting); WebBrowser = new ChromiumWebBrowser ("https://www.baidu.com"); // The initial Page WebBrowser. registerJsObject ("jsObj", new JsEvent (), new CefSharp. bindingOptions () {CamelCaseJavascriptNames = false}); // Interactive Data WebBrowser. dock = DockStyle. fill; // Fill the WebBrowser. dock = DockStyle. fill; // set the dock mode this. controls. add (WebBrowser); // Add form} private void Form1_Load (object sender, EventArgs e) {} private void button#click (object sender, EventArgs e) {WebBrowser. load (textBox1.Text); // browse URL} private async void button2_Click (object sender, EventArgs e) {await WebBrowser. getBrowser (). mainFrame. evaluateScriptAsync ("test_val =" + new Random (). next (). toString ("F"); // set the test_val variable of js on the page to a random number await WebBrowser. getBrowser (). mainFrame. evaluateScriptAsync ("test ()"); // run the js test method on the page} private async void button3_Click (object sender, EventArgs e) {await WebBrowser. getBrowser (). mainFrame. evaluateScriptAsync ("testArg ('201312', 'net ')"); // run the testArg method with parameters on js on the page} public class JsEvent {public string MessageText {get; set;} public void ShowTest () {MessageBox. show ("this in C #. \ n \ r "+ MessageText);} public void ShowTestArg (string ss) {MessageBox. show ("received JS with parameter call \ n \ r" + ss );}}}

In the form constructor, set the basic settings of the browser and fill the window

Refresh button to access the URL in the input box

Js interaction button to run the js program on the page

JsEvent is the JS interaction interface on the page.

Next, we will write a test asp page.

Create a blank ASP project GoogleTestWeb

Create an html page HtmlPage1 with the following code:

<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "> <title> </title> <meta charset =" UTF-8 "> <script src =" https://code.jquery.com/jquery-2.1.4.min.js "> </script> <script> var test_val; function test () {alert ("Net program event received" + test_val);} function testArg (d1, d2) {alert ("Net program event received 1" + d1 ); alert ("Net program event received 2" + d2);} $ (function () {$ ('button: eq (0 )'). on ("click", BtnClick); $ ('button: eq (1 )'). on ("click", BtnClickArgs);}) function BtnClick () {if (typeof jsObj = "undefined") {alert ("jsObj Parameter not initialized") return ;} jsObj. messageText = "I am js"; jsObj. showTest ();} function BtnClickArgs () {if (typeof jsObj = "undefined") {alert ("jsObj Parameter not initialized") return;} jsObj. showTestArg ($ ('textarea: eq (0 )'). val () ;}</script> <button style = "margin-top: 100px "> send to Net Program </button> <button> send to Net program with parameters </button> <textarea> </textarea>

Generate the project. The Code has been written.

The next step is to test

Right-click the HTML page and click View in the browser. VS will open the browser and perform the html page

Copy the URL. Here is https: // localhost: 54562/HtmlPage1.html.

Run the previous winform program, copy the URL to textBox, and click Refresh. The page will be displayed after a moment.

Click JS interaction (call js functions from winform)

Click js interaction with parameters (call js functions with parameters from winform)

Click to send to net program

Click send to Net program with parameters (input parameters next)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.