前端时间,写过一篇博文:《 C#动态编译,实现按钮功能动态配置》,里面提到了动态编译的好处,可以随时添加你要集成的功能,而不用去重新启动系统。如果系统超级大,启动需要半个小时甚至数个小时的话,用动态编译是极佳的选择。
动态编译的好处让我舍不得丢弃它,所以只好找方法来优化它了。既然每次点击需要编译,如果我把全部功能都一次性编译完毕,保存这个实例,然后每次点击,都通过这个实例去调用对应的方法,这样就完美解决了这一问题。
不多说,上代码:
动态编译类 Evaluator:
using System; using System.IO; using System.Text; using System.CodeDom.Compiler; using System.Windows.Forms; using Microsoft.CSharp; using System.Reflection; namespace CashierSystem { /// <summary> /// 本类用来将字符串转为可执行文本并执行,用于动态定义按钮响应的事件。 /// </summary> public class Evaluator { private string filepath = Path.Combine(Application.StartupPath, "FunBtn.config"); #region 构造函数 /// <summary> /// 可执行串的构造函数 /// </summary> /// <param name="items">可执行字符串数组</param> public Evaluator(EvaluatorItem[] items) { ConstructEvaluator(items); //调用解析字符串构造函数进行解析 } /// <summary> /// 可执行串的构造函数 /// </summary> /// <param name="returnType">返回值类型</param> /// <param name="expression">执行表达式</param> /// <param name="name">执行字符串名称</param> public Evaluator(Type returnType, string expression, string name) { //创建可执行字符串数组 EvaluatorItem[] items = { new EvaluatorItem(returnType, expression, name) }; ConstructEvaluator(items); //调用解析字符串构造函数进行解析 } /// <summary> /// 可执行串的构造函数 /// </summary> /// <param name="item">可执行字符串项</param> public Evaluator(EvaluatorItem item) { EvaluatorItem[] items = { item };//将可执行字符串项转为可执行字符串项数组 ConstructEvaluator(items); //调用解析字符串构造函数进行解析 } /// <summary> /// 解析字符串构造函数 /// </summary> /// <param name="items">待解析字符串数组</param> private void ConstructEvaluator(EvaluatorItem[] items) { //创建C#编译器实例 //ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler()); CSharpCodeProvider comp = new CSharpCodeProvider(); //编译器的传入参数 CompilerParameters cp = new CompilerParameters(); Configer configer = Configer.Current(filepath); string[] assemblies = configer.GetAssembly("FunBtn//assembly//dll","name"); cp.ReferencedAssemblies.AddRange(assemblies); //添加程序集集合 cp.GenerateExecutable = false; //不生成可执行文件 cp.GenerateInMemory = true; //在内存中运行 StringBuilder code = new StringBuilder(); //创建代码串 /* * 添加常见且必须的引用字符串 */ //获取引用的命名空间 string[] usings = configer.GetAssembly("FunBtn//assembly//using", "name"); foreach (var @using in usings) { code.Append(@using+"\n");//添加引用的命名空间 } code.Append("namespace EvalGuy { \n"); //生成代码的命名空间为EvalGuy,和本代码一样 code.Append(" public class _Evaluator { \n"); //产生 _Evaluator 类,所有可执行代码均在此类中运行 foreach (EvaluatorItem item in items) //遍历每一个可执行字符串项 { code.AppendFormat(" public {0} {1}() ", //添加定义公共函数代码 item.ReturnType.Name.ToLower() , //函数返回值为可执行字符串项中定义的返回值类型 item.Name); //函数名称为可执行字符串项中定义的执行字符串名称 code.Append("{ "); //添加函数开始括号 if (item.ReturnType.Name == "Void") { code.AppendFormat("{0};", item.Expression);//添加函数体,返回可执行字符串项中定义的表达式的值 } else { code.AppendFormat("return ({0});", item.Expression);//添加函数体,返回可执行字符串项中定义的表达式的值 } code.Append("}\n"); //添加函数结束括号 } code.Append("} }"); //添加类结束和命名空间结束括号 //得到编译器实例的返回结果 CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString()); if (cr.Errors.HasErrors) //如果有错误 { StringBuilder error = new StringBuilder(); //创建错误信息字符串 error.Append("编译有错误的表达式: "); //添加错误文本 foreach (CompilerError err in cr.Errors) //遍历每一个出现的编译错误 { error.AppendFormat("{0}\n", err.ErrorText); //添加进错误文本,每个错误后换行 } throw new Exception("编译错误: " + error.ToString());//抛出异常 } Assembly a = cr.CompiledAssembly; //获取编译器实例的程序集 _Compiled = a.CreateInstance("EvalGuy._Evaluator"); //通过程序集查找并声明 EvalGuy._Evaluator 的实例 } #endregion #region 公有成员 /// <summary> /// 执行字符串并返回整型值 /// </summary> /// <param name="name">执行字符串名称</param> /// <returns>执行结果</returns> public int EvaluateInt(string name) { return (int)Evaluate(name); } /// <summary> /// 执行字符串并返回字符串型值 /// </summary> /// <param name="name">执行字符串名称</param> /// <returns>执行结果</returns> public string EvaluateString(string name) { return (string)Evaluate(name); } /// <summary> /// 执行字符串并返回布尔型值 /// </summary> /// <param name="name">执行字符串名称</param> /// <returns>执行结果</returns> public bool EvaluateBool(string name) { return (bool)Evaluate(name); } /// <summary> /// 执行字符串并返 object 型值 /// </summary> /// <param name="name">执行字符串名称</param> /// <returns>执行结果</returns> public object Evaluate(string name) { MethodInfo mi = _Compiled.GetType().GetMethod(name);//获取 _Compiled 所属类型中名称为 name 的方法的引用 return mi.Invoke(_Compiled, null); //执行 mi 所引用的方法 } public void EvaluateVoid(string name) { MethodInfo mi = _Compiled.GetType().GetMethod(name);//获取 _Compiled 所属类型中名称为 name 的方法的引用 mi.Invoke(_Compiled, null); //执行 mi 所引用的方法 } #endregion #region 静态成员 /// <summary> /// 执行表达式并返回整型值 /// </summary> /// <param name="code">要执行的表达式</param> /// <returns>运算结果</returns> static public int EvaluateToInteger(string code) { Evaluator eval = new Evaluator(typeof(int), code, staticMethodName);//生成 Evaluator 类的对像 return (int)eval.Evaluate(staticMethodName); //执行并返回整型数据 } /// <summary> /// 执行表达式并返回字符串型值 /// </summary> /// <param name="code">要执行的表达式</param> /// <returns>运算结果</returns> static public string EvaluateToString(string code) { Evaluator eval = new Evaluator(typeof(string), code, staticMethodName);//生成 Evaluator 类的对像 return (string)eval.Evaluate(staticMethodName); //执行并返回字符串型数据 } /// <summary> /// 执行表达式并返回布尔型值 /// </summary> /// <param name="code">要执行的表达式</param> /// <returns>运算结果</returns> static public bool EvaluateToBool(string code) { Evaluator eval = new Evaluator(typeof(bool), code, staticMethodName);//生成 Evaluator 类的对像 return (bool)eval.Evaluate(staticMethodName); //执行并返回布尔型数据 } /// <summary> /// 执行表达式并返回 object 型值 /// </summary> /// <param name="code">要执行的表达式</param> /// <returns>运算结果</returns> static public object EvaluateToObject(string code) { Evaluator eval = new Evaluator(typeof(object), code, staticMethodName);//生成 Evaluator 类的对像 return eval.Evaluate(staticMethodName); //执行并返回 object 型数据 } /// <summary> /// 执行表达式并返回 void 空值 /// </summary> /// <param name="code">要执行的表达式</param> static public void EvaluateToVoid(string code) { Evaluator eval = new Evaluator(typeof(void), code, staticMethodName);//生成 Evaluator 类的对像 eval.EvaluateVoid(staticMethodName); //执行并返回 object 型数据 } #endregion #region 私有成员 /// <summary> /// 静态方法的执行字符串名称 /// </summary> private const string staticMethodName = "ExecuteBtnCommand"; /// <summary> /// 用于动态引用生成的类,执行其内部包含的可执行字符串 /// </summary> object _Compiled = null; #endregion } /// <summary> /// 可执行字符串项(即一条可执行字符串) /// </summary> public class EvaluatorItem { /// <summary> /// 返回值类型 /// </summary> public Type ReturnType; /// <summary> /// 执行表达式 /// </summary> public string Expression; /// <summary> /// 执行字符串名称 /// </summary> public string Name; /// <summary> /// 可执行字符串项构造函数 /// </summary> /// <param name="returnType">返回值类型</param> /// <param name="expression">执行表达式</param> /// <param name="name">执行字符串名称</param> public EvaluatorItem(Type returnType, string expression, string name) { ReturnType = returnType; Expression = expression; Name = name; } } }
//配置文件路径名称 private string filePath = Path.Combine(Application.StartupPath, "FunBtn.config"); //文件路径 //用于动态编译功能 private Evaluator eval = null;
同时,要有一次性编译功能的方法
/// <summary> /// 一次性编译所有按钮的功能 /// </summary> public void CreateFun() { //创建配置类 Configer configer = Configer.Current(filePath); //获取按钮名称,执行代码,返回值 string[] name = configer.GetNodeProperties("FunBtn//btndetail//btn", "name"); string[] code = configer.GetNodeProperties("FunBtn//btndetail//btn", "code"); string[] returnType = configer.GetNodeProperties("FunBtn//btndetail//btn", "returntype"); //创建可执行字符串数组 EvaluatorItem[] items = new EvaluatorItem[name.Length]; for (int i = 0; i < items.Length; i++) { items[i] = new EvaluatorItem(GetTypeByString(returnType[i]), code[i], name[i]); } //一次性初始化全部按钮 eval = new Evaluator(items); //调用解析字符串构造函数进行解析 }
读写配置文件类Configer:
using System.Drawing; using System.IO; using System.Windows.Forms; using System.Xml; namespace CashierSystem { /// <summary> /// 负责读写应用程序配置文件,即app.config的读写。 /// </summary> public class Configer { #region 私有成员 private string version; //版本号 private string updatetime; //更新时间 private string isautoupdate; //是否自动更新 private string funbtnwidth; //功能区按钮宽度 private string funbtnheight; //功能区按钮高度 private string expandbtnwidth; //扩展区按钮宽度 private string expandbtnheight; //扩展区按钮高度 //private string btnname; //按钮名称 //private string btntext; //按钮显示文本 //private string btntype; //按钮类型 //private string btnleft; //左边距 //private string btntop; //上边距 //private string btnreturntype; //返回值类型 //private string btncode; //调用代码 private string arrange; //扩展区按钮布局 private string firstleft; //第一个按钮的左边距 private string firsttop; //第一个按钮的上边距 private string horizontal; //水平间距 private string vertical; //垂直间距 private string filePath; //文件路径 private static Configer current; //唯一实例 #endregion /// <summary> /// 因为不需要多个实例,所以采用了单例模式,由Current属性来获取唯一的实例 /// </summary> /// <param name="filepath">文件Url</param> private Configer(string filepath) { this.filePath = filepath; //version = GetNodeProperty("FunBtn//info", "version"); //updatetime = GetNodeProperty("FunBtn//info", "updatetime"); ; //isautoupdate = GetNodeProperty("FunBtn//info", "isautoupdate"); //funbtnwidth = GetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "width"); //funbtnheight = GetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "height"); //expandbtnwidth = GetNodeProperty("FunBtn//btnsetting//set[@name='expandbtn']", "width"); //expandbtnheight = GetNodeProperty("FunBtn//btnsetting//set[@name='expandbtn']", "height"); } /// <summary> /// 获取当前配置。 /// </summary> /// <param name="filepath">配置文件路径</param> /// <returns>返回唯一实例</returns> public static Configer Current(string filepath) { if (current == null) { current = new Configer(filepath); } //current = new Configer(filepath); return current; } #region 基本配置信息 /// <summary> /// 获取基本信息 /// </summary> public void GetInfo() { version = GetNodeProperty("FunBtn//info", "version"); updatetime = GetNodeProperty("FunBtn//info", "updatetime"); ; isautoupdate = GetNodeProperty("FunBtn//info", "isautoupdate"); funbtnwidth = GetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "width"); funbtnheight = GetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "height"); expandbtnwidth = GetNodeProperty("FunBtn//btnsetting//set[@name='expandbtn']", "width"); expandbtnheight = GetNodeProperty("FunBtn//btnsetting//set[@name='expandbtn']", "height"); } /// <summary> /// 版本号 /// </summary> public string Version { get { return version; } set { SetNodeProperty("FunBtn//info", "version", value); } } /// <summary> /// 更新时间 /// </summary> public string UpdateTime { get { return updatetime; } set { SetNodeProperty("FunBtn//info", "updatetime", value); } } /// <summary> /// 是否自动更新 /// </summary> public string IsAutoUpdate { get { return isautoupdate; } set { SetNodeProperty("FunBtn//info", "isautoupdate", value); } } /// <summary> /// 功能区按钮宽度 /// </summary> public string FunBtnWidth { get { return funbtnwidth; } set { SetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "width", value); } } /// <summary> /// 功能区按钮高度 /// </summary> public string FunBtnHeight { get { return funbtnheight; } set { SetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "height", value); } } /// <summary> /// 扩展区按钮宽度 /// </summary> public string ExpandBtnWidth { get { return expandbtnwidth; } set { SetNodeProperty("FunBtn//btnsetting//set[@name='expandbtn']", "width", value); } } /// <summary> /// 扩展区按钮高度 /// </summary> public string ExpandBtnHeight { get { return expandbtnheight; } set { SetNodeProperty("FunBtn//btnsetting//set[@name='expandbtn']", "height", value); ; } } #endregion #region 按钮配置信息 public struct BtnInfo { public string BtnName;//按钮名称 public string BtnText; //按钮显示文本 public string BtnType; //按钮类型 public string BtnLeft; //左边距 public string BtnTop; //上边距 public string BtnReturnType; //返回值类型 public string BtnCode; //调用代码 } /// <summary> /// 获取按钮信息 /// </summary> public BtnInfo GetBtnInfo(string btnName) { var btnInfo = new BtnInfo();//定义一个btn信息结构 btnInfo.BtnName = GetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "name"); btnInfo.BtnText = GetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "value"); btnInfo.BtnType = GetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "type"); btnInfo.BtnLeft = GetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "left"); btnInfo.BtnTop = GetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "top"); btnInfo.BtnReturnType = GetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "returntype"); btnInfo.BtnCode = GetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "code"); return btnInfo; } /// <summary> /// 设置按钮信息 /// </summary> public void SetBtnInfo(string btnName, BtnInfo btnInfo) { SetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "value", btnInfo.BtnText); SetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "type", btnInfo.BtnType); SetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "left", btnInfo.BtnLeft); SetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "top", btnInfo.BtnTop); SetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "returntype", btnInfo.BtnReturnType); SetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "code", btnInfo.BtnCode); SetNodeProperty("FunBtn//btndetail//btn[@name='" + btnName + "']", "name", btnInfo.BtnName); } #endregion #region 特定功能部分 /// <summary> /// 显示树形结构中的功能 /// </summary> /// <param name="tree"></param> public void ShowButtons(TreeView tree) { if (!File.Exists(filePath)) return; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); //清空所有节点 tree.Nodes.Clear(); //获取根节点 XmlNodeList nodelist = xmlDoc.SelectNodes("FunBtn//btnsetting//set"); if (nodelist != null) { foreach (var VARIABLE in nodelist) { TreeNode node = new TreeNode(); XmlAttributeCollection xmlAttributeCollection = ((XmlNode)VARIABLE).Attributes; if (xmlAttributeCollection != null) { //添加根节点:功能区和扩展区 node.Name = xmlAttributeCollection["name"].Value; node.Text = xmlAttributeCollection["value"].Value; //添加所属的子节点 ShowChildBtn(node, node.Name); tree.Nodes.Add(node); } } } tree.ExpandAll();//全部展开 } /// <summary> /// 根据按钮类型,将其子项加载到给定的节点中 /// </summary> /// <param name="treeNode">父节点</param> /// <param name="btnType">按钮类型</param> private void ShowChildBtn(TreeNode treeNode, string btnType) { if (!File.Exists(filePath)) return; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); //获取按钮信息设置 var selectSingleNode = xmlDoc.SelectNodes("FunBtn//btndetail//btn[@type='" + btnType + "']"); if (selectSingleNode != null) { XmlNodeList nodelist = selectSingleNode; foreach (var VARIABLE in nodelist) { TreeNode node = new TreeNode(); XmlAttributeCollection xmlAttributeCollection = ((XmlNode)VARIABLE).Attributes; if (xmlAttributeCollection != null) { //添加功能区或扩展区的所属功能按钮 node.Name = xmlAttributeCollection["name"].Value; node.Text = xmlAttributeCollection["value"].Value; treeNode.Nodes.Add(node); } } } } /// <summary> /// 按钮信息 /// </summary> public struct BtnArray { public int Size; //可显示按钮数量 public int RowsCount; //行数 public int ColsCount; //列数 public int Horizontal; //水平间距 public int Vertical; //垂直间距 public int FirstLeft; //第一个按钮左边距 public int FirstTop; //第一个按钮上边距 public int Width; //宽度 public int Height; //高度 } /// <summary> /// 往控件中加载按钮 /// </summary> /// <param name="control">控件</param> /// <param name="path">节点路径</param> /// <param name="btnArray">要生成按钮的信息</param> public void LoadButton(Control control, string path, BtnArray btnArray) { if (!File.Exists(filePath)) return; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); //排列位置,第一个按钮左边距,上边距,列数,水平间距,垂直间距,宽度,高度 int rank = 0, firstleft = 0, firsttop = 0, colsCount = 0, horizontal = 0, vertical = 0, width = 0, height = 0; firstleft = btnArray.FirstLeft;//第一个按钮左边距 firsttop = btnArray.FirstTop;//第一个按钮上边距 colsCount = btnArray.ColsCount;//列数 horizontal = btnArray.Horizontal;//水平间距 vertical = btnArray.Vertical; //垂直间距 width = btnArray.Width;//宽度 height = btnArray.Height;//高度 //获取按钮节点 XmlNodeList nodelist = xmlDoc.SelectNodes(path); if (nodelist != null) { for (int i = 0; i < nodelist.Count; i++) { XmlAttributeCollection xmlAttributeCollection = nodelist[i].Attributes; if (xmlAttributeCollection != null) { rank = int.Parse(xmlAttributeCollection["rank"].Value); //获取排列位置 if (rank == -1 || rank >= btnArray.Size) continue;//rank为-1或者超过显示额度时,则不显示。 Button btn = new Button(); //计算每个按钮的坐标 int x = firstleft + (rank % colsCount) * (horizontal + width); int y = firsttop + (rank / colsCount) * (vertical + height); //添加根节点:功能区和扩展区 btn.Name = xmlAttributeCollection["name"].Value;//按钮名称 btn.Text = xmlAttributeCollection["value"].Value;//按钮显示文本 btn.Location = new Point(x, y);//设定按钮位置跟矩形框一致 btn.Size = new Size(width + 1, height + 1);//设定按钮大小比矩形框略大1 btn.Tag = rank;//记录第几个位置 control.Controls.Add(btn); btn.BringToFront();//置顶按钮 } } } } /// <summary> /// 为节点列表的特定属性写入相同的值 /// </summary> /// <param name="path">路径</param> /// <param name="nodeProperty">属性名</param> public string[] GetAssembly(string path, string nodeProperty) { if (!File.Exists(filePath)) return null; var xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); string[] assemblies = null; //获取节点列表 XmlNodeList nodelist = xmlDoc.SelectNodes(path); if (nodelist != null) { //根据节点个数,实例化数组,用于存在引用的dll名称 assemblies = new string[nodelist.Count]; for (int i = 0; i < nodelist.Count; i++)//遍历列表 { var element = (XmlElement)nodelist[i]; assemblies[i] = element.GetAttribute(nodeProperty);//装载dll到数组中 } } return assemblies;//返回数组 } #endregion /// <summary> /// 获取节点值 /// </summary> /// <param name="path">节点路径</param> /// <param name="nodeProperty">节点名称</param> /// <returns>属性值</returns> public string GetNodeProperty(string path, string nodeProperty) { XmlDocument doc = new XmlDocument(); //加载文件 doc.Load(filePath); XmlElement element = null; //节点元素 element = (XmlElement)(doc.SelectSingleNode(path)); if (element != null) { return element.GetAttribute(nodeProperty); } else { return " "; } } /// <summary> /// 获取节点值 /// </summary> /// <param name="path">节点路径</param> /// <param name="nodeProperty">节点名称</param> /// <returns>属性值</returns> public string[] GetNodeProperties(string path, string nodeProperty) { XmlDocument doc = new XmlDocument(); //加载文件 doc.Load(filePath); //获取根节点 XmlNodeList nodelist = doc.SelectNodes(path); string[] result= new string[nodelist.Count]; if (nodelist != null) { int i=0; foreach (var VARIABLE in nodelist) { TreeNode node = new TreeNode(); XmlAttributeCollection xmlAttributeCollection = ((XmlNode)VARIABLE).Attributes; if (xmlAttributeCollection != null) { //获取节点中的某项属性值,加入到数组中 result[i] = xmlAttributeCollection[nodeProperty].Value; i++; } } } return result; } /// <summary> /// 写入属性值 /// </summary> /// <param name="path">节点路径</param> /// <param name= "nodeProperty"> 属性名称</param> /// <param name= "nodeValue">属性值</param> public void SetNodeProperty(string path, string nodeProperty, string nodeValue) { var doc = new XmlDocument(); //加载文件 doc.Load(filePath); XmlElement element = null; //获取版本信息 element = (XmlElement)(doc.SelectSingleNode(path)); if (element != null) { //给某个属性写入值 element.SetAttribute(nodeProperty, nodeValue); } doc.Save(filePath); } /// <summary> /// 获取节点值 /// </summary> /// <param name="path">节点路径</param> /// <param name="nodeProperty">节点名称</param> /// <returns>属性值</returns> public string GetNodeValue(string path, string nodeProperty) { XmlDocument doc = new XmlDocument(); //加载文件 doc.Load(filePath); XmlNode node = null; //获取节点 node = (doc.SelectSingleNode(path)); if (node != null) { //返回节点内容 return node.Value; } else { return " "; } } /// <summary> /// 写入节点值 /// </summary> /// <param name="path">节点路径</param> /// <param name= "nodeProperty"> 属性名称</param> /// <param name= "nodeValue">属性值</param> public void SetNodeValue(string path, string nodeProperty, string nodeValue) { var doc = new XmlDocument(); //加载文件 doc.Load(filePath); XmlNode node = null; //获取节点 node = (doc.SelectSingleNode(path)); if (node != null) { //在节点中写入内容 node.Value = nodeValue; } doc.Save(filePath); } /// <summary> /// 为节点列表的特定属性写入相同的值 /// </summary> /// <param name="path">路径</param> /// <param name="nodeProperty">属性名</param> /// <param name="nodeValue">属性值</param> public void SetAllNodeProperty(string path, string nodeProperty, string nodeValue) { if (!File.Exists(filePath)) return; var xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); //获取节点列表 var selectSingleNode = xmlDoc.SelectNodes(path); if (selectSingleNode != null) { XmlNodeList nodelist = selectSingleNode; foreach (var VARIABLE in nodelist)//遍历列表 { XmlElement element = (XmlElement)VARIABLE; //((XmlElement)VARIABLE).Attributes[nodeProperty].Value = nodeValue; element.SetAttribute(nodeProperty, nodeValue); } } xmlDoc.Save(filePath); } /// <summary> /// 创建节点 /// </summary> /// <param name="path">父节点路径</param> /// <param name="name">节点名称</param> /// <param name="nodeProperties">属性数组</param> /// <param name="nodeValues">属性值数组</param> public void CreateNode(string path,string name, string[] nodeProperties, string[] nodeValues) { if (!File.Exists(filePath)) return; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); //获取按钮信息设置 var selectSingleNode = xmlDoc.SelectSingleNode(path); if (selectSingleNode != null) { XmlElement xmlElement = xmlDoc.CreateElement(name); //遍历属性数组,一次添加 for (int i = 0; i < nodeProperties.Length; i++) { //添加属性 xmlElement.SetAttribute(nodeProperties[i], nodeValues[i]); } selectSingleNode.AppendChild(xmlElement); } xmlDoc.Save(filePath);//保存 } /// <summary> /// 移除节点 /// </summary> /// <param name="path">父节点路径</param> /// <param name="name">子节点名称</param> public void RemoveNode(string path,string name) { if (!File.Exists(filePath)) return; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); //获取父节点 var selectSingleNode = xmlDoc.SelectSingleNode(path); if (selectSingleNode != null) { //获取子节点 var node=selectSingleNode.SelectSingleNode(name); if (node != null) { selectSingleNode.RemoveChild(node); } } xmlDoc.Save(filePath);//保存 } } }
配置文件App.Config文件:
<?xml version="1.0" encoding="utf-8"?> <FunBtn> <!-- 版本信息 --> <info version="1.00" updatetime="2013-01-01 10:00:00.123" isautoupdate="true" /> <!-- 引用的程序集和命名空间 --> <assembly> <dll name="system.dll" /> <dll name="system.data.dll" /> <dll name="system.xml.dll" /> <dll name="system.windows.forms.dll" /> <dll name="IBLL.dll" /> <dll name="BLL.dll" /> <dll name="Entity.dll" /> <dll name="LED_Model.dll" /> <dll name="FunButton.dll" /> <dll name="CashierSystem.exe" /> <using name="using System;" /> <using name="using System.Data;" /> <using name="using System.Data.SqlClient;" /> <using name="using System.Data.OleDb;" /> <using name="using System.Xml;" /> <using name="using FunButton;" /> <using name="using CashierSystem;" /> <using name="using System.Windows.Forms;" /> </assembly> <!-- 按钮大小设置 --> <btnsetting> <set name="funbtn" value="功能区按钮" width="105" height="60" /> <set name="expandbtn" value="扩展区按钮" width="135" height="60" /> <arrange name="2x4" firstleft="10" firsttop="5" horizontal="25" vertical="15" /> <arrange name="3x3" firstleft="30" firsttop="25" horizontal="115" vertical="85" /> <arrange name="3x4" firstleft="30" firsttop="25" horizontal="70" vertical="24" /> <arrange name="4x3" firstleft="30" firsttop="40" horizontal="30" vertical="65" /> <arrange name="4x4" firstleft="30" firsttop="25" horizontal="30" vertical="24" /> <more using="4x4" /> </btnsetting> <!-- 按钮属性和方法 --> <btndetail> <btn name="btnDelOrder" value="删除订单" type="funbtn" rank="1" left="140" top="5" returntype="void" code="new FunBtn().DelOrder(frmMain.frm);" /> <btn name="btnCheckOut" value="结 账" type="funbtn" rank="0" left="10" top="5" returntype="void" code="new FunBtn().CheckOut(frmMain.frm)" /> <btn name="btnClose" value="退出" type="funbtn" rank="2" left="10" top="80" returntype="void" code="Application.Exit()" /> <btn name="btnDelAllOrder" value="整单删除" type="funbtn" rank="3" left="140" top="80" returntype="void" code="new FunBtn().DelAllOrder(frmMain.frm);" /> <btn name="btnMore" value="更 多" type="funbtn" rank="6" left="10" top="230" returntype="void" code="new FunBtn().More(frmMain.frm)" /> <btn name="btnHangOrder" value="挂 单" type="funbtn" rank="4" left="10" top="155" returntype="void" code="new FunBtn().HangOrder(frmMain.frm)" /> <btn name="btnGetOrder" value="取 单" type="funbtn" rank="5" left="140" top="155" returntype="void" code="new FunBtn().GetOrder()" /> <btn name="btnOpenCashBox" value="开钱箱" type="funbtn" rank="-1" left="140" top="230" returntype="void" code="new FunBtn().OpenCashBox(frmMain.frm)" /> <btn name="btnReprint" value="重打" type="expandbtn" rank="6" left="360" top="109" returntype="void" code="new FunBtn().RePrint()" /> <btn name="btnCheckCash" value="下班交款" type="expandbtn" rank="0" left="30" top="25" returntype="void" code="new FunBtn().CheckCash()" /> <btn name="btnQueryMember" value="会员查询" type="expandbtn" rank="2" left="360" top="25" returntype="void" code="new FunBtn().QueryMember()" /> <btn name="btnLock" value="锁屏" type="expandbtn" rank="5" left="195" top="109" returntype="void" code="new FunBtn().Lock()" /> <btn name="btnMemberMgr" value="会员管理" type="expandbtn" rank="1" left="195" top="25" returntype="void" code="new FunBtn().MemberMgr()" /> <btn name="btnRegister" value="会员注册" type="expandbtn" rank="9" left="195" top="193" returntype="void" code="new FunBtn().Register()" /> <btn name="btnRecharge" value="会员充值" type="expandbtn" rank="10" left="360" top="193" returntype="void" code="new FunBtn().Recharge()" /> <btn name="btnLockCard" value="会员挂失" type="expandbtn" rank="-1" left="30" top="10" returntype="void" code="new FunBtn().LockCard()" /> <btn name="btnQueryConsume" value="消费查询" type="expandbtn" rank="-1" left="30" top="277" returntype="void" code="new FunBtn().QueryConsume()" /> <btn name="btnModifyPwd" value="修改密码" type="expandbtn" rank="4" left="30" top="109" returntype="void" code="new FunBtn().ModifyPwd()" /> <btn name="btnQuit" value="返 回" type="expandbtn" rank="15" left="525" top="277" returntype="void" code="new FunBtn().Quit()" /> <btn name="btnExit" value="退 出" type="expandbtn" rank="13" left="195" top="277" returntype="void" code="new FunBtn().Exit(frmMain.frm)" /> <btn name="btnReturnOrder" value="退 单" type="expandbtn" rank="3" left="525" top="25" returntype="void" code="new FunBtn().ReturnOrder()" /> <btn name="btnSetAuth" value="授权管理" type="expandbtn" rank="-1" left="195" top="315" returntype="void" code="new FunBtn().SetAuth(frmMain.frm)" /> <btn name="btnQueryRecharge" value="充值查询" type="expandbtn" rank="-1" left="30" top="277" returntype="void" code="new FunBtn().QueryRecharge()" /> <btn name="btnReStart" value="重新启动" type="expandbtn" rank="12" left="30" top="277" returntype="void" code="Application.Restart()" /> <btn name="btnRunSet" value="环境设置" type="expandbtn" rank="7" left="525" top="109" returntype="void" code="new FunBtn().RunSet()" /> <btn name="btnLogOut" value="注 销" type="expandbtn" rank="14" left="360" top="277" returntype="void" code="new FunBtn().LogOut(frmMain.frm)" /> <btn name="btnQueryUser" value="查询用户" type="expandbtn" rank="-1" left="360" top="25" returntype="void" code="new FunBtn().QueryUser()" /> <btn name="btnUpdate" value="软件升级" type="expandbtn" rank="8" left="30" top="193" returntype="void" code="new FunBtn().Update()" /> <btn name="btnBtnSetting" value="功能设置" type="expandbtn" rank="11" left="525" top="193" returntype="void" code="new FunBtn().BtnSetting()" /> <btn name="btnReLoadGoodsType" value="刷新菜系" type="funbtn" rank="7" left="140" top="230" returntype="void" code="new FunBtn().ReLoadGoodsType(frmMain.frm)" /> </btndetail> </FunBtn>
一切准备完毕后,在界面中添加按钮,并给每个按钮赋予事件:
/// <summary> /// 往承载区加载按钮 /// </summary> private void LoadButtons() { try { Configer configer = Configer.Current(filePath); Configer.BtnArray btnArray = new Configer.BtnArray();//按钮信息 btnArray.Size = 8; //可显示数 btnArray.RowsCount = 4; //列数 btnArray.ColsCount = 2; //列数 btnArray.Horizontal = int.Parse(configer.GetNodeProperty("FunBtn//btnsetting//arrange[@name='2x4']", "horizontal")); //水平间距 btnArray.Vertical = int.Parse(configer.GetNodeProperty("FunBtn//btnsetting//arrange[@name='2x4']", "vertical")); //垂直间距 btnArray.FirstLeft = int.Parse(configer.GetNodeProperty("FunBtn//btnsetting//arrange[@name='2x4']", "firstleft")); //第一个按钮左边距 btnArray.FirstTop = int.Parse(configer.GetNodeProperty("FunBtn//btnsetting//arrange[@name='2x4']", "firsttop")); //第一个按钮上边距 btnArray.Width = int.Parse(configer.GetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "width")); //宽度 btnArray.Height = int.Parse(configer.GetNodeProperty("FunBtn//btnsetting//set[@name='funbtn']", "height")); ; //高度 //加载功能按钮 configer.LoadButton((System.Windows.Forms.Control)Panel1, "FunBtn//btndetail//btn[@type='funbtn']", btnArray); AddBtnEvent();//添加事件 } catch (Exception exception) { MessageBox.Show(exception.Message); } }
/// <summary> /// 为按钮添加click事件 /// </summary> private void AddBtnEvent() { //遍历按钮 foreach (Button VARIABLE in Panel1.Controls) { VARIABLE.Click += Button_Click; } } /// <summary> /// 为动态生成的功能区按钮定义click事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void Button_Click(object sender, EventArgs e) { try { //根据按钮名称,调用对应的方法 eval.Evaluate(((Button)sender).Name); #region 多次编译(旧代码) //Configer configer = Configer.Current(filePath); //string code = configer.GetNodeProperty( // "FunBtn//btndetail//btn[@name='" + ((Button)sender).Name + "']", "code"); //string returnType = // configer.GetNodeProperty("FunBtn//btndetail//btn[@name='" + ((Button)sender).Name + "']", // "returntype"); //switch (returnType) //{ // case "void": // Evaluator.EvaluateToVoid(code); // break; // case "object": // Evaluator.EvaluateToObject(code); // break; // case "int": // Evaluator.EvaluateToInteger(code); // break; // case "bool": // Evaluator.EvaluateToBool(code); // break; // case "string": // Evaluator.EvaluateToString(code); // break; //} #endregion } catch (Exception exception) { MessageBox.Show(exception.Message); } }
到此为止,代码已经共享完毕了。或许大家看到这大段大段的代码很头疼,没着急,我给你简单的说说:
大概看几幅效果图片吧。