WinForm使用CefSharp,嵌入浏览器
【摘要】
引入库:CefSharp.WinForms
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using Sys...
引入库:CefSharp.WinForms
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 大屏Win
{
public partial class Form1 : Form
{
static string url = System.Configuration.ConfigurationManager.AppSettings["url"].ToString();//从配置文件中读取要打开的url
static ChromiumWebBrowser chromeBrowser = null;
public Form1()
{
InitializeComponent();
try
{
CefSettings settings = new CefSettings();
settings.Locale = "zh-CN";//中文环境
settings.AcceptLanguageList = "zh-CN";//中文环境
settings.CachePath = System.IO.Directory.GetCurrentDirectory()+"\\cache";//设置缓存
Cef.Initialize(settings);
chromeBrowser = new ChromiumWebBrowser(url);
chromeBrowser.AddressChanged += Browser_AddressChanged;//监听地址变化
this.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
//js和cs交互
chromeBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
chromeBrowser.JavascriptObjectRepository.Register("yfcsobj", new yfcsobj(), isAsync: true, options: BindingOptions.DefaultBinder);
chromeBrowser.ExecuteScriptAsync("refreshdata()");//c# 调用 js方法
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.Exit();
}
}
private void Browser_AddressChanged(object sender, AddressChangedEventArgs e)
{
//MessageBox.Show(e.Address);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
//监听键盘按键
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.F12)
{
chromeBrowser.ShowDevTools();//打开调试模式
}
}
}
}
public class yfcsobj
{
public void test(string msg)
{
MessageBox.Show(msg);
}
public void closeApp()
{
//彻底关闭进程
System.Environment.Exit(0);
Application.Exit();
}
}
html中使用
<html>
<body>
<button onclick="test()">test</button>
<button onclick="test2()">test2</button>
<script>
function test(){
yfcsobj.test('test js');
}
function test2(){
yfcsobj.closeApp();
}
</script>
</body>
<html>
文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。
原文链接:zzzili.blog.csdn.net/article/details/115760080
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)