Skip to content

Instantly share code, notes, and snippets.

@MartinBspheroid
Last active March 6, 2020 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartinBspheroid/2c1cc7196381ed3fd7deb8a9b7173b76 to your computer and use it in GitHub Desktop.
Save MartinBspheroid/2c1cc7196381ed3fd7deb8a9b7173b76 to your computer and use it in GitHub Desktop.
Comunication between C# and javaScript in CEF
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using CefSharp.WinForms;
using CefSharp;
// This is the code for your desktop app.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
namespace DesktopApp1
{
public partial class Form1 : Form
{
public ChromiumWebBrowser browser;
public class CallbackObj
{
public void showMessage(string msg)
{
// do whatever
Console.WriteLine(msg);
}
public void getImage(string imgData)
{
using (Image image = Image.FromStream(new MemoryStream(Convert.FromBase64String(GetBase64FromJavaScriptImage(imgData)))))
{
// <parameters> : path / format
image.Save("output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
/// From https://dejanstojanovic.net/aspnet/2018/january/javascript-base64-image-to-bitmap-in-c/
public static String GetBase64FromJavaScriptImage(String imgData)
{
return Regex.Match(imgData, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
}
}
public void InitBrowser()
{
CefSettings settings = new CefSettings();
settings.CefCommandLineArgs.Add("enable-media-stream", "1");
Cef.Initialize(settings);
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
browser = new ChromiumWebBrowser("localhost:3000");
browser.JavascriptObjectRepository.Register("callbackObj", new CallbackObj(), isAsync: false, options: BindingOptions.DefaultBinder);
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
}
public Form1()
{
InitializeComponent();
InitBrowser();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Click on the link below to continue learning how to build a desktop app using WinForms!
System.Diagnostics.Process.Start("http://aka.ms/dotnet-get-started-desktop");
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Thanks!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment