0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cscの作法 その590

Posted at

概要

cscの作法、調べてみた。
webview2見つけたので、やってみた。

参考にしたページ

写真

image.png

サンプルコード

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());
		}
	}
}





以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?