概要
cscの作法、調べてみた。
webview2見つけたので、やってみた。
参考にしたページ
写真
サンプルコード
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SampleWebView2Form
{
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class JsToCs {
public void MessageShow(string strText) {
MessageBox.Show("Jsからの呼び出し>" + strText);
}
}
public partial class Form1: Form {
private WebView2 WebView = new WebView2 {
Source = new Uri("file:///C:/Users/ore/csc/sample.html"),
};
private JsToCs CsClass = new JsToCs();
public Form1() {
this.Controls.Add(WebView);
WebView.Size = this.Size;
this.SizeChanged += Form1_SizeChanged;
WebView.NavigationCompleted += WebView_NavigationCompleted;
}
private void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) {
try
{
if (WebView.CoreWebView2 != null)
{
WebView.CoreWebView2.AddHostObjectToScript("class", CsClass);
CsToJs();
}
else
MessageBox.Show("CoreWebView2==null");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private async void CsToJs() {
string str1 = await WebView.ExecuteScriptAsync("func1(\"C#からの呼び出し\")");
MessageBox.Show("Jsからの戻り値>" + str1);
}
private void Form1_SizeChanged(object sender, EventArgs e) {
WebView.Size = this.Size;
}
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
以上。