Demo要求
1、在页面上设计一个计算器的相关按钮;
2、从本地读取xml并解析展示在页面上(xml中的内容自拟);
3、在页面上显示需要计算的数值,然后在后台计算好传到页面上显示,实现winform与js的交互;
下面给出Demo的例子:可能会有Bug大家勿喷
步骤:
新建一个Windows窗体应用程序:Form1
新建一个html文件(关于计算页面的)tang.htm
新建xml文件(后台程序重xml文件中读取内容)first.xml
运行截图
1.窗体程序代码
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;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.IO;
namespace WinForms2
{
//在被调用方法类上加上[ComVisible(true)]标签,意思就是当前类可以以com组件的形式供外包调用
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisible(true)]
public partial class Form1 : Form
{
//在他的构造方法里写代码
public Form1()
{
InitializeComponent();
//第一种:打开项目路径中的htm文件 // Application.StartupPath + "\\" + "test.htm";
//需要将html文件放在debug文件下面 使用DirectoryInfo需要导入 using System.IO;
DirectoryInfo mDir = new DirectoryInfo(Application.StartupPath);
DirectoryInfo mDirF = mDir.Parent.Parent;
//MessageBox.Show(mDirF.FullName);
string pathName = mDirF.FullName + "\\" + "tang.htm";
//初始化webBrowser,保证js和C#通信
this.webBrowser1.ObjectForScripting = this;
//加载指定网页资源
webBrowser1.Navigate(pathName);
//调用自定的方法读取xml文件中的内容
getXml();
}
string title = "";
//读取xml中的文件
public void getXml()
{
//将XML文件加载进来 XDocument这个要想不报错,要导入using System.Xml.Linq;
try {
//将XML文件加载进来 为了写文件路径的\不要加转义符而在前面加上@标识符
XDocument document = XDocument.Load("../../first.xml");
//获取到XML的根元素进行操作
// XDocument document = XDocument.Load(Application.StartupPath + "\\" + "first.xml");
XElement root = document.Root;
XElement ele = root.Element("Note");
//获取info标签的值
XElement info = ele.Element("info");
title = info.Value;
}catch (Exception e){
MessageBox.Show(e.Message);
}
}
object obj="";
public string Computer(String str)
{
//因为反斜杠需要转义,所以会有两个\\ 这是检查传入的字符串是否符合运算规则
string pattern = "^-{0,}\\d+(\\.*\\d{0,})([+*/-]\\d+(\\.*\\d{0,}))+$";
Regex re = new Regex(pattern);
//判断传入的字符串是否正则表达式的规则
if(re.IsMatch(str))
{ //如果匹配则进行计算
DataTable dt = new DataTable();
obj=(dt.Compute(str, ""));
//MessageBox.Show(obj.ToString());
}