一、背景说明:
很多外设通信需要串口,通过C#开发串口通信程序非常方便,但是将C#数据引入浏览器非常繁琐,而且开发Activex只有IE能够完美兼容。B/S模式开发的系统移动性好的同时,操作外设困难。
然而,将JSP或HTML加载到C#窗体程序很方便,而且JS和C#通信很简单。
二、C#和JS之间的相互调用
1.新建项目
2.添加控件
3.最终效果如图
三、程序源码
新建一个txt文件,将扩展名改成html,然后将下面HTML源码复制进去,用浏览器打开,将地址复制下来,写到 webBrowser1.Url = new Uri(URL)里
- C#窗体部分
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WebBrowser
{
//设置Com对外可访问
[System.Runtime.InteropServices.ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 将当前类设置为可由脚本访问
webBrowser1.ObjectForScripting = this;
}
private void Form1_Load(object sender, EventArgs e)
{
//可以从TextBox里获取Url
webBrowser1.Url = new Uri("file:///C:/Users/Administrator/Desktop/ConnectC.html");
}
private void button1_Click(object sender, EventArgs e)
{
SendMessage();
}
#region**Connect JS**
//被外部js调用的方法
public void MyMessageBox(string message)
{
textBox1.Text = message;
}
private void SendMessage()
{
// 调用JavaScript的messageBox方法,并传入参数
object[] objects = new object[1];
objects[0] = textBox2.Text;
webBrowser1.Document.InvokeScript("GetMessage", objects);
}
#endregion
}
}
- html页面部分
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'ConnectC#.jsp' starting page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
</style>
<script language="javascript" type="text/javascript">
/* 调用C#方法 */
function SendMessage(){
window.external.MyMessageBox(document.getElementById("send").value);
}
<!-- 提供给C#程序调用的方法,接收返回值 -->
function GetMessage(message)
{
//alert(message);
document.getElementById("arrive").value = message;
}
</script>
</head>
<body>
<input type="button" value="发送数据" onclick="SendMessage();" style="width:200px;height:30px;"/>
<br><br>
<h2>要发送的数据</h2><input style="width:200px;height:30px;" id="send"/>
<h2>接收到的数据</h2><input style="width:200px;height:30px;" id="arrive"/>
</body>
</html>