1 引用

  • CefSharp.Common v100.0.230

  • CefSharp.WinForms v100.0.230

2 初始化

1
2
3
4
5
6
7
8
9
loginForm = new LoginForm();//承载页面的Form窗体
string url = AppDomain.CurrentDomain.BaseDirectory + @"\html\login.html";//请求页面地址
ChromiumWebBrowser webCom = new ChromiumWebBrowser(url);//传入地址,实例化页面对象
CefSharpSettings.WcfEnabled = true;//注册绑定在页面的操作类
webCom.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
webCom.JavascriptObjectRepository.Register("middleware", this, isAsync: false, options: BindingOptions.DefaultBinder);
webCom.Dock = DockStyle.Fill;//指定页面停靠位置和方式
webCom.Load(url);//加载页面
loginForm.Controls.Add(webCom);

3 Winform方法声明与数据接收、处理

1
2
3
4
5
6
7
8
9
10
11
12
public bool sysLogin(string strData)
{
//把字符串转化成objectJson对象取值
JObject jsonObj = JsonConvert.DeserializeObject<JObject>(strData);
//从页面获得的数据里取值
object username = jsonObj["userName"];
object password = jsonObj["passWord"];
if (username != null || password != null/* || string.IsNullOrEmpty(username.ToString()) || string.IsNullOrEmpty(password.ToString())*/)
return false;
MessageBox.Show($"用户名:{username} 密码{password}");
return true;
}

4 HTML方法调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$('#btnLogin').click(function (formData) {
var objUsername = document.getElementById("username");
var objPassword = document.getElementById("password");
var strUsername = objUsername.value;
var strPassword = objPassword.value;
if (strUsername != null && strUsername != null && strPassword != "" && strPassword != "" && strPassword != undefined) {
var data = {
'userName': strUsername,
'passWord': strPassword
}
var formData = middleware.sysLogin(JSON.stringify(data));
if (formData != null) {
alert(JSON.stringify(formData));
return;
}
}
});