通用工业视觉软件设计之C#脚本-后端-初始化更新UI
一 窗口加载函数
public ModuleFrm()
{
InitializeComponent();
this.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight - 16;
this.MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
this.Loaded += ModuleFrm_Loaded;
}
private ModuleObj frm_ModuleObj;
public string InCode = "";
private void ModuleFrm_Loaded(object sender, RoutedEventArgs e)
{
frm_ModuleObj = (ModuleObj)m_ModuleObjBase;
Title.HeadName = frm_ModuleObj.ModuleParam.ModuleName;
CurrentModelID = frm_ModuleObj.ModuleParam.ModuleName;
m_MyEditer.Text = frm_ModuleObj.InCode;
InitializeMethodDictionary();
InitScintilla();
InitTxt();
}
private void InitializeMethodDictionary()
{
methodDic.Add("Show", new ScriptMethodInfo
{
Name = "Show",
Description = "void Show(string content)",
Category = "MessageBox",
DisplyName = "Show"
});
}
初始化显示代码控件
private void InitScintilla()
{
m_MyEditer.WrapMode = WrapMode.None;
InitSyntaxColoring(m_MyEditer);
m_MyEditer.AutoCIgnoreCase = true;
AutoComplete();
m_MyEditer.ClearCmdKey(Keys.Control | Keys.S);
m_MyEditer.ClearCmdKey(Keys.Control | Keys.F);
m_MyEditer.AutoCCompleted += m_MyEditer_AutoCCompleted;
}
初始化显示提示文本
private void InitTxt()
{
string str = "\"";
string str1 = "\"," + str;
#region C#基本语法
RichtxtboxInput(System.Windows.Media.Brushes.Green, "C#基本语法");
#endregion
}
内部支持方法-ScriptMethods
添加引用

创建文件夹-05_VisionManage
OperDataVar
using ModuleDataVar;
using ModulePublicShare;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ModuleLog;
namespace VisionCore
{
public class OperDataVar
{
public static object obj = new object();
public static void UpdateGlobalValue(ref List<DataVar> inVariableList, DataVar data)
{
lock (obj)
{
int index = inVariableList.FindIndex(c => c.m_DataName == data.m_DataName);
if (index > -1)
{
inVariableList[index] = data;
}
else
{
inVariableList.Add(data);
}
}
}
public static object GetGlobalValue(string ValueName)
{
lock (obj)
{
int index = SysProcessSln.g_VarList.FindIndex(c => c.m_DataName == ValueName);
if (index > -1)
{
return SysProcessSln.g_VarList[index].m_DataValue;
}
Log.Error("未查询到对应的变量名!");
return null;
}
}
public static DataVar GetGlobalValueBackData(string ValueName)
{
lock (obj)
{
int index = SysProcessSln.g_VarList.FindIndex(c => c.m_DataName == ValueName);
if (index > -1)
{
return SysProcessSln.g_VarList[index];
}
Log.Error("未查询到对应的变量名!");
return new DataVar();
}
}
}
}
ScriptMethods
using HalconDotNet;
using ModuleDataVar;
using ModuleLog;
using ModulePublicShare;
using ModuleView;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml.Linq;
using VisionCore;
namespace Plugin.CSharpScript
{
public class ScriptMethods
{
public int ProjectID { get; set; } = 0;
public string ModuleName { get; set; }
public void Show(string str)
{
MessageBox.Show(str);
}
public void LogInfo(string str)
{
Log.Info(str);
}
public string GenDateTime(string format)
{
return System.DateTime.Now.ToString(format);
}
public void ShowHwindowText(string ProjectName, string ModuleName, string ModuleDescribe, string Txt, string color)
{
int proIndex = SysProcessSln.g_ProjectList.FindIndex(c => c.ProjectInfo.m_ProjectName == ProjectName);
if (proIndex > -1)
{
int index = -1;
index = SysProcessSln.g_ProjectList[proIndex].m_ModuleObjList.FindIndex(c => c.ModuleParam.ModuleName == ModuleName);
if (index > -1)
{
ModuleParam par = SysProcessSln.g_ProjectList[proIndex].m_ModuleObjList[index].ModuleParam;
ModuleROIText 结果 = new ModuleROIText(
par.ToString(),
par.ToString(),
ModuleDescribe,
ModuleRoiType.文字显示.ToString(),
color,
Txt,
24);
if (SysProcessSln.g_ProjectList[proIndex].m_ModuleObjList[index].m_Image != null)
{
SysProcessSln.g_ProjectList[proIndex].m_ModuleObjList[index].m_Image.UpdateTxtList(结果);
}
else
{
Log.Error("对应的Himage为Null!");
}
}
}
}
public object GetGlobalValue(string ValueName)
{
return OperDataVar.GetGlobalValue(ValueName);
}
public void SetGlobalValue(string ValueName, object obj)
{
bool Conver = false;
int index = SysProcessSln.g_VarList.FindIndex(c => c.m_DataName == ValueName);
if (index > -1)
{
switch (SysProcessSln.g_VarList[index].m_DataType)
{
case DataVarType.DataType.Int:
Conver = obj is int;
break;
case DataVarType.DataType.Double:
if (double.TryParse(obj.ToString(), out double result))
{
Conver = true;
}
else
{
Conver = false;
}
break;
case DataVarType.DataType.Float:
Conver = obj is float;
break;
case DataVarType.DataType.Bool:
Conver = obj is bool;
break;
case DataVarType.DataType.String:
Conver = obj is String;
break;
default:
break;
}
DataVar objStatus;
if (SysProcessSln.SaveUpValue)
{
objStatus = new DataVar(SysProcessSln.g_VarList[index].m_DataAtrr, SysProcessSln.g_VarList[index].m_DataModuleID,
SysProcessSln.g_VarList[index].m_DataName, SysProcessSln.g_VarList[index].m_DataType, SysProcessSln.g_VarList[index].m_DataGroup,
SysProcessSln.g_VarList[index].m_Data_Num, obj.ToString(), SysProcessSln.g_VarList[index].m_DataTip, obj);
}
else
{
objStatus = new DataVar(SysProcessSln.g_VarList[index].m_DataAtrr, SysProcessSln.g_VarList[index].m_DataModuleID,
SysProcessSln.g_VarList[index].m_DataName, SysProcessSln.g_VarList[index].m_DataType, SysProcessSln.g_VarList[index].m_DataGroup,
SysProcessSln.g_VarList[index].m_Data_Num, SysProcessSln.g_VarList[index].m_Data_InitValue, SysProcessSln.g_VarList[index].m_DataTip, obj);
}
if (Conver)
{
VisionCore.OperDataVar.UpdateGlobalValue(ref SysProcessSln.g_VarList, objStatus);
}
else
{
Log.Error("C#脚本模块,根据变量名称设置变量值,转换格式错误,请查询接收变量类型是否与输入变量类型一致!");
}
}
else
{
Log.Error("未查询到对应的变量名!");
}
}
public object GetModuleValue(string ProjectName, string ModuleName, string ModuleVar)
{
int proIndex = SysProcessSln.g_ProjectList.FindIndex(c => c.ProjectInfo.m_ProjectName == ProjectName);
if (proIndex > -1)
{
int index = -1;
index = SysProcessSln.g_ProjectList[proIndex].m_Var_List.FindIndex(c => c.m_DataTip == ModuleName && c.m_DataName == ModuleVar);
if (index > -1)
{
return SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataValue;
}
else
{
Log.Error("未查询到对应的模块!");
return 0;
}
}
else
{
Log.Error("未查询到对应的流程!");
return 0;
}
}
public void SetModuleValue(string ProjectName, string ModuleName, string ModuleVar, object obj)
{
bool Conver = false;
int proIndex = SysProcessSln.g_ProjectList.FindIndex(c => c.ProjectInfo.m_ProjectName == ProjectName);
if (proIndex > -1)
{
int index = -1;
index = SysProcessSln.g_ProjectList[proIndex].m_Var_List.FindIndex(c => c.m_DataTip == ModuleName && c.m_DataName == ModuleVar);
if (index > -1)
{
switch (SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataType)
{
case DataVarType.DataType.Int:
Conver = obj is int;
break;
case DataVarType.DataType.Double:
if (double.TryParse(obj.ToString(), out double result))
{
Conver = true;
}
else
{
Conver = false;
}
break;
case DataVarType.DataType.Float:
Conver = obj is float;
break;
case DataVarType.DataType.Bool:
Conver = obj is bool;
break;
case DataVarType.DataType.String:
Conver = obj is String;
break;
default:
break;
}
DataVar objStatus = new DataVar(
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataAtrr,
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataModuleID,
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataName,
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataType,
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataGroup,
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_Data_Num,
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_Data_InitValue,
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index].m_DataTip,
obj);
if (Conver)
{
SysProcessSln.g_ProjectList[proIndex].m_Var_List[index] = objStatus;
}
else
{
Log.Error("C#脚本模块,设置模块的值,转换格式错误,请查询接收变量类型是否与输入变量类型一致!");
}
}
else
{
Log.Error("未查询到对应的模块!");
}
}
else
{
Log.Error("未查询到对应的流程!");
}
}
public string JsonRead(string InputStr, string selectVale)
{
JObject jObj = JObject.Parse(InputStr);
JToken ageToken = jObj[selectVale];
string str = ageToken.ToString();
return str;
}
public string JsonRead(string InputStr, string selectVale, string subValue)
{
JObject jObj = JObject.Parse(InputStr);
JToken ageToken = jObj[selectVale];
string str = ageToken[subValue].ToString();
return str;
}
public string JsonWriteArray(Object Input)
{
List<string> obj1 = (List<string>)Input;
JObject staff = new JObject()
{
new JProperty("command", "T1_1"),
new JProperty("run_result", 1),
};
List<JObject> InoutPbj = new List<JObject>();
for (int i = 0; i < obj1.Count; i++)
{
InoutPbj.Add(new JObject
{
new JProperty("battery_index", i),
new JProperty("result",Convert.ToInt32( obj1[i]))
});
}
staff.Add(new JProperty("results", InoutPbj.ToArray()));
string json = JsonConvert.SerializeObject(staff);
Console.WriteLine(json.ToString());
return json;
}
public bool Intersection(string ProjectName1, string ModelName1, string ProjectName2, string ModelName2, int Index)
{
try
{
HRegion hRegion = (HRegion)GetModuleValue(ProjectName1, ModelName1, "区域");
HRegion hRegion1 = (HRegion)GetModuleValue(ProjectName2, ModelName2, "区域");
hRegion = hRegion.SelectObj(Index + 2);
HRegion outRegion = hRegion.Intersection(hRegion1);
int AreaNum = outRegion.AreaCenter(out double row, out double col);
return AreaNum > 0;
}
catch (Exception)
{
return false;
}
}
}
}
高亮规则
public static System.Drawing.Color IntToColor(int rgb)
{
return System.Drawing.Color.FromArgb(255, (byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
}
private void InitSyntaxColoring(Scintilla scintilla)
{
scintilla.StyleResetDefault();
scintilla.Styles[ScintillaNET.Style.Default].Font = "Consolas";
scintilla.Styles[ScintillaNET.Style.Default].Size = 10;
scintilla.Styles[ScintillaNET.Style.Default].ForeColor = System.Drawing.Color.Black;
scintilla.StyleClearAll();
scintilla.ScrollWidth = 100;
scintilla.Styles[ScintillaNET.Style.Cpp.Comment].ForeColor = ColorTranslator.FromHtml("#008000");
scintilla.Styles[ScintillaNET.Style.Cpp.Number].ForeColor = ColorTranslator.FromHtml("#FF6532");
scintilla.Styles[ScintillaNET.Style.Cpp.String].ForeColor = ColorTranslator.FromHtml("#A31515");
scintilla.Styles[ScintillaNET.Style.Cpp.Preprocessor].ForeColor = IntToColor(0x8AAFEE);
scintilla.Styles[ScintillaNET.Style.Cpp.Operator].ForeColor = ColorTranslator.FromHtml("#A31515");
scintilla.Lexer = Lexer.Cpp;
scintilla.Styles[ScintillaNET.Style.LineNumber].ForeColor = ColorTranslator.FromHtml("#8DA3C1");
var nums = scintilla.Margins[1];
nums.Width = 30;
nums.Type = MarginType.Number;
nums.Sensitive = true;
nums.Mask = 0;
}
代码提示功能
private string m_AutoStr;
public void AutoComplete()
{
m_MyEditer.CharAdded += Scintilla_CharAdded;
string s = GetMethodsString();
string str = " " + s;
List<string> autoStrList = str.Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).ToList();
m_AutoStr = string.Join(" ", autoStrList.OrderBy(x => x.ToUpper()));
}
private void Scintilla_CharAdded(object sender, CharAddedEventArgs e)
{
var currentPos = m_MyEditer.CurrentPosition;
var wordStartPos = m_MyEditer.WordStartPosition(currentPos, true);
var lenEntered = currentPos - wordStartPos;
if (lenEntered > 0)
{
if (!m_MyEditer.AutoCActive)
{
m_MyEditer.AutoCShow(lenEntered, m_AutoStr);
}
}
}
获取当前程序集指定方法:GetMethodsString
public string GetMethodsString()
{
List<string> strList = new List<string>();
List<Type> typeList = new List<Type>();
typeList.Add(typeof(Object));
typeList.Add(typeof(Math));
typeList.Add(typeof(string));
typeList.Add(typeof(System.Collections.Generic.List<double>));
typeList.Add(typeof(Enumerable));
typeList.Add(typeof(System.Windows.MessageBox));
typeList.Add(typeof(ScriptMethods));
foreach (Type item in typeList)
{
if (item.IsEnum == true)
{
string[] rolearry = Enum.GetNames(item);
strList.AddRange(rolearry);
strList.Add(item.Name);
}
else
{
MethodInfo[] methods = item.GetMethods();
foreach (MethodInfo m in methods)
{
strList.Add(m.ToString().Split(' ')[1].Split('(')[0].Replace("set_", "").Replace("get_", "").Split('[')[0]);
}
strList.Add(item.Name);
}
}
return string.Join(" ", strList.Distinct().ToList().OrderBy(x => x.ToUpper())); ;
}
private Dictionary<string, ScriptMethodInfo> methodDic = new Dictionary<string, ScriptMethodInfo>();
ScriptTemplate
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Plugin.CSharpScript
{
class ScriptMethodInfo
{
public string Name;
public string Description;
public string Category;
public string DisplyName;
}
public class ScriptTemplate
{
public static string s_RawScript =
@"
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using HalconDotNet;
using Plugin.CSharpScript;
using System.Windows.Forms;
public class MyScript
{
public void Process()
{
MessageBox.Show(""Test Run!"");
ScriptMethods methods = new ScriptMethods();
methods.LogInfo(""运行成功!"");
}
}
";
public static string GetScriptCode(string code)
{
if (code.Length > 0) return code;
return s_RawScript;
}
public static string CSharpString()
{
string str1 = " ";
string str2 = " ";
return str1 + str2;
}
}
}
private void m_MyEditer_AutoCCompleted(object sender, AutoCSelectionEventArgs e)
{
string tip = ShowTipByWord();
if (!string.IsNullOrWhiteSpace(tip))
{
m_MyEditer.CallTipShow(m_MyEditer.CurrentPosition, tip);
}
}
private string ShowTipByWord()
{
var currentPos = m_MyEditer.CurrentPosition;
var wordStartPos = m_MyEditer.WordStartPosition(currentPos, true);
var wordEndPos = m_MyEditer.WordEndPosition(currentPos, true);
string word = m_MyEditer.GetTextRange(wordStartPos, wordEndPos - wordStartPos);
string tip = "";
if (!string.IsNullOrWhiteSpace(word))
{
if (methodDic.ContainsKey(word))
{
tip = methodDic[word].Description;
tb_Compile.Text = tip;
}
}
return tip;
}
初始化文本内容
private void InitTxt()
{
string str = "\"";
string str1 = "\"," + str;
#region C#基本语法
RichtxtboxInput(System.Windows.Media.Brushes.Green, "C#基本语法");
#endregion
}
private void RichtxtboxInput(System.Windows.Media.Brush brush, string txt)
{
Run item = new Run(txt);
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(item);
paragraph.LineHeight = 1.0;
paragraph.Foreground = brush;
this.Txt_Tip.Document.Blocks.Add(paragraph);
}