using PaintDotNet.Base.SettingModel;
using PaintDotNet.Base.CommTool;
using PaintDotNet.DbOpreate.DbBll;
using PaintDotNet.DbOpreate.DbModel;
using PaintDotNet.ImageCollect;
using PaintDotNet.SystemLayer;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Configuration;
using SenseShield;
using System.Drawing;
using Metis.ParameterSet;
using PaintDotNet.Annotation;
using PaintDotNet.Base;
using StageController;
using System.IO.Ports;
using PaintDotNet.Camera;
using OpenCvSharp;
using Metis;
namespace PaintDotNet
{
internal sealed class Startup
{
public static Startup instance;
public SplashForm splashForm = null;
///
/// 启动时传进来的参数,需要进行解析
/// 在自定义快捷方式的时候会用到
/// 读取不同的配置路径的配置信息
///
private string[] args;
///
/// 主窗体
///
private MainForm mainForm;
///
/// 设置信息所在的文件夹
///
public string SettingPrefix = "Default";
///
/// 常规设置-用户信息
///
public UserInfoModel userInfo;
///
/// 常规设置-网格信息
///
public GridModel gridModel;
///
/// 系统配置
///
public ConfigModel configModel;
///
/// 载物台配置
///
public LoadingStageModel loadingStageModel;
///
/// 快捷键配置
///
public HotkeyModel hotkeyModel;
///
/// 工具栏
///
public ToolbarModel toolbarModel;
///
/// 工具栏坐标
///
//public ToolbarLocationModel toolbarLocationModel;
///
/// 水印配置
///
public WatermarkModel watermarkModel;
///
/// 工字线配置
///
public WorkTypeStyleModel workTypeStyleModel;
///
/// 标尺配置
///
public RulerModel rulerModel;
///
/// 工作流程
///
public WorkFlowModel workFlowModel;
///
/// 快捷栏
///
public ShortcutbarModel shortcutbarModel;
///
/// 标注样式信息
///
public LabelStyleModel labelStyleModel;
///
/// 测量样式信息
///
public MeasureStyleModel measureStyleModel;
///
/// 设置-常规设置-辅助线样式信息
///
public GuideStyleModel guideStyleModel;
///
/// 换算完的标尺信息,包含所有系统内得单位
///
public Dictionary rules = new Dictionary();
///
/// 系统内选定的单位
///
public MeasurementUnit measurementUnit;
///
/// 相机参数
///
public CameraParamModel cameraParamModel;
///
/// 当前系统标尺
///
public mic_rulers ruleDB;
///
/// 标尺集合
///
public List mic_rulersAll;
///
/// 单位对应的枚举数字
///
public Dictionary companyEnume;
///
/// 工艺图比照
///
public ArtworkModel artworkModel;
///
/// 电动偏光设置
///
public MotorizedLightModel motorizedLightModel;
///
/// 电压设置
///
public VoltageModel voltageModel;
///
/// 图像处理参数
///
public ImageMenu imageMenuModel;
///
/// 二值处理参数
///
public ImageMenu binaryActionModel;
///
/// 是否开启加密锁验证
///
private static/*const*/ bool useSenseShield = false;//true;//
private static bool haveShowSenseAlert = false;
///
/// 将value为FALSE的菜单隐藏显示,key为要隐藏的menuID
///
private static Dictionary shieldValue = new Dictionary();
public static bool showNsegExtraction = true;//控制是否显示晶界重现菜单
public int step_length = 1;
///
/// 是否启用大图
///
public bool useBigFile = true;
///
/// 构造函数
///
///
private Startup(string[] args)
{
Application.SetCompatibleTextRenderingDefault(false);
Application.EnableVisualStyles();
//先单独获取App基础配置
configModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Config.xml", FileMode.Open));
PdnResources.Initialize(configModel);
if (configModel.StartImgStatus == 2)
{
this.splashForm = new SplashForm(configModel.StartImg);
var width = Screen.PrimaryScreen.WorkingArea.Width;
var height = Screen.PrimaryScreen.WorkingArea.Height;
this.splashForm.Location = new System.Drawing.Point(width / 2 - 300, height / 2 - 200);
this.splashForm.TopMost = true;
this.splashForm.Show();
this.splashForm.Update();
}
this.args = args;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["DBEntities"].ConnectionString = "Data Source=" + Application.StartupPath + @"\microscope.db3";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
//用于EF暖机操作,以避免第一次度数据库过慢
using (var dbcontext = new PaintDotNet.DbOpreate.DBEntities())
{
var objectContext = ((IObjectContextAdapter)dbcontext).ObjectContext;
var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace);
mappingCollection.GenerateViews(new List());
}
if (useBigFile)
{
//设置内存映射文件的路径,回头考虑写到配置文件,或者检测空闲最大的磁盘
//Mat.SetMappingFilePath("d://");
//设置最大像素值后采用内存映射文件
//Mat.SetMaxPixelSize(MemoryBlock.bigFile);
}
}
///
/// 启动一个实例
///
///
/// 是否需要管理员权限
/// 传递进来的参数
public static void StartNewInstance(IWin32Window parent, bool requireAdmin, string[] args)
{
StringBuilder allArgsSB = new StringBuilder();
foreach (string arg in args)
{
allArgsSB.Append(' ');
if (arg.IndexOf(' ') != -1)
{
allArgsSB.Append('"');
}
allArgsSB.Append(arg);
if (arg.IndexOf(' ') != -1)
{
allArgsSB.Append('"');
}
}
string allArgs;
if (allArgsSB.Length > 0)
{
allArgs = allArgsSB.ToString(1, allArgsSB.Length - 1);
}
else
{
allArgs = null;
}
Shell.Execute(
parent,
Application.ExecutablePath,
allArgs,
requireAdmin ? ExecutePrivilege.RequireAdmin : ExecutePrivilege.AsInvokerOrAsManifest,
ExecuteWaitType.ReturnImmediately);
}
///
/// 检查需要的文件是否存在
/// 并且尝试修复
///
///
/// 返回true则说明缺少东西
/// 返回false则说明都正常
///
private bool CheckForImportantFiles()
{
string[] requiredFiles =
new string[]
{
"ICSharpCode.SharpZipLib.dll",
"PaintDotNet.Base.dll",
"PaintDotNet.Core.dll",
"PaintDotNet.Data.dll",
"PaintDotNet.Resources.dll",
"PaintDotNet.Strings.3.DE-DE.resources",
"PaintDotNet.Strings.3.EN-US.resources",
"PaintDotNet.Strings.3.ZH-CN.resources",
"PaintDotNet.SystemLayer.dll",
"SetupNgen.exe",
"ShellExtension_x64.dll",
"ShellExtension_x86.dll"
/*"Squish_x64.dll",
"Squish_x86.dll",
"Squish_x86_SSE2.dll"*/
};
string dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
List missingFiles = null;
foreach (string requiredFile in requiredFiles)
{
bool missing;
try
{
string pathName = Path.Combine(dirName, requiredFile);
FileInfo fileInfo = new FileInfo(pathName);
missing = !fileInfo.Exists;
}
catch (Exception)
{
missing = true;
}
if (missing)
{
if (missingFiles == null)
{
missingFiles = new List();
}
missingFiles.Add(requiredFile);
}
}
if (missingFiles == null)
{
return false;
}
else
{
if (Shell.ReplaceMissingFiles(missingFiles.ToArray()))
{
// Everything is repaired and happy.
return true;
}
else
{
// Things didn't get fixed. Bail.
Process.GetCurrentProcess().Kill();
return false;
}
}
}
public void Start()
{
Process[] app = Process.GetProcessesByName("Metis");
if (app.Length > 1)
{
//added begin by songxk
//杀掉进程,启动metis
for (int i = 0; i < app.Length - 1; i++)
{
var ap = app[i];
ap.Kill();
}
//added end by songxk
}
// Initialize some misc. Windows Forms settings
//StartAnimation();
// If any files are missing, try to repair.
// However, support /skipRepairAttempt for when developing in the IDE
// so that we don't needlessly try to repair in that case.
//if (this.args.Length > 0 &&
// string.Compare(this.args[0], "/skipRepairAttempt", StringComparison.InvariantCultureIgnoreCase) == 0)
//{
// // do nothing: we need this so that we can run from IDE/debugger
// // without it trying to repair itself all the time
//}
//else
//{
// if (CheckForImportantFiles())
// {
// Startup.StartNewInstance(null, true, args);
// return;
// }
//}
StartPart2();
}
///
/// 设置语言、地区等
///
private void StartPart2()
{
InitCameraManager();
InitStageController();
string locale = Settings.CurrentUser.GetString(SettingNames.LanguageName, null);
if (locale == null)
{
locale = Settings.SystemWide.GetString(SettingNames.LanguageName, null);
}
if (locale != null)
{
try
{
CultureInfo ci = new CultureInfo(locale, true);
Thread.CurrentThread.CurrentUICulture = ci;
}
catch (Exception)
{
// Don't want bad culture name to crash us
}
}
// Check system requirements
if (!OS.CheckOSRequirement())
{
string message = PdnResources.GetString("Error.OSRequirement");
Utility.ErrorBox(null, message);
return;
}
// Parse command-line arguments
if (this.args.Length == 1) // && this.args[0] == Updates.UpdatesOptionsDialog.CommandLineParameter
{
//Updates.UpdatesOptionsDialog.ShowUpdateOptionsDialog(null, false);
}
else
{
SingleInstanceManager singleInstanceManager = new SingleInstanceManager("hero");
// If this is not the first instance of PDN.exe, then forward the command-line
// parameters over to the first instance.
if (!singleInstanceManager.IsFirstInstance)
{
singleInstanceManager.FocusFirstInstance();
foreach (string arg in this.args)
{
singleInstanceManager.SendInstanceMessage(arg, 30);
}
singleInstanceManager.Dispose();
singleInstanceManager = null;
return;
}
// Create main window
this.mainForm = new MainForm(this.args);
this.mainForm.SingleInstanceManager = singleInstanceManager;
singleInstanceManager = null; // mainForm owns it now
if (useSenseShield)
StartPart3();
// 3 2 1 go
Application.Run(this.mainForm);
try
{
this.mainForm.Dispose();
CameraManager.GetInstance().UnInitManager();
AxisController.GetInstance().Close();
}
catch (Exception)
{
}
this.mainForm = null;
}
}
///
/// 设置定时方法
///
private void StartPart3()
{
//主线程中启动一个支线程,执行doSomething这样的一个方法。
Thread thread = new Thread(new ThreadStart(ThreadRun));
thread.IsBackground = true;//这样能随主程序一起结束
thread.Start();
//Console.ReadKey();
}
delegate void Delegate_do();
private void ThreadRun()
{
try
{
Delegate_do Delegate_do = new Delegate_do(FindAllProduct);
Thread.Sleep(30000);//隔30秒后判断一下是否完成
IAsyncResult result = Delegate_do.BeginInvoke(null, null);
while (!result.IsCompleted)
{
Console.WriteLine("子线程未完成2");
Thread.Sleep(10000);//每隔10秒判断一下是否完成
}
Console.WriteLine("-------子线程已完成-------");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void FindAllProduct()
{
List moduleList = new List() { 1 };
while (true)
{
try
{
uint[] moduleIds = moduleList.ToArray();
moduleIds = DogDecrypting.decryptingModules(4/*, moduleIds*/);//第一个参数固定为4
Console.WriteLine("颁发许可发现。");
}
catch (Exception ex)
{
if (!haveShowSenseAlert)
{
Console.WriteLine("发现错误:" + ex.Message);
haveShowSenseAlert = true;
ShowMessage(ex.Message);
}
while (senseShieldAutoLoop(moduleList) == false)
{
Console.WriteLine("仍然错误:颁发许可未发现");
System.Threading.Thread.Sleep(20);
}
}
Console.WriteLine("子线程未完成1");
Thread.Sleep(10000);//每隔10秒判断一下是否发现颁发许可
}
}
private bool senseShieldAutoLoop(List moduleList)
{
try
{
uint[] moduleIds = moduleList.ToArray();
moduleIds = DogDecrypting.decryptingModules(4/*, moduleIds*/);//第一个参数固定为4
}
catch (Exception ex)
{
if (!haveShowSenseAlert)
{
haveShowSenseAlert = true;
ShowMessage(ex.Message);
}
return false;
}
return true;
}
private void ShowMessage(string msg)
{
this.mainForm.Invoke(new MessageBoxShow(MessageBoxShow_F), new object[] { msg });
}
delegate void MessageBoxShow(string msg);
void MessageBoxShow_F(string msg)
{
if (MessageBox.Show(msg, "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
haveShowSenseAlert = false;
}
///
/// 程序主入口
///
[STAThread]
public static int Main(string[] args)
{
//instance = new Startup(args);
//instance.ModifySettingPrefix(args);
//instance.SystemReset();
//instance.InitSetting();
//Application.Run(new Preview2.Preview2Dialog());
//return 1;
//这是要求管理员权限的版本
/*//当前用户是管理员的时候,直接启动应用程序
//如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
//创建Windows用户主题
Application.EnableVisualStyles();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
//Application.EnableVisualStyles();
//Application.Run(new Form1());
instance = new Startup(args);
instance.ModifySettingPrefix(args);
instance.SystemReset();
instance.InitSetting();
instance.Start();
// 为了测试用
if (System.IO.File.Exists(Application.StartupPath + @"\1.txt"))
useSenseShield = true;
if (useSenseShield)
{
shieldValue.Clear();
try
{
//1.生成目录下需要有4个运行库,分别在x64和x86下,每个里面两个
//2.在C#项目里引用SlmRuntimeCsharp.dll
//3.插入加密狗,执行代码测试
uint[] moduleIds = DogDecrypting.decryptingModules(4*//*, moduleIds*//*);//第一个参数固定为4
//this.label2.Text = string.Format("加密狗内许可模块号:{0}{1}", Environment.NewLine, string.Join(",", moduleIds));
foreach (uint menuId in moduleIds)
if (!shieldValue.ContainsKey(menuId))
shieldValue.Add(menuId, true);
else
shieldValue[menuId] = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return 0;
}
}
instance = new Startup(args);
instance.ModifySettingPrefix(args);
instance.SystemReset();
instance.InitSetting();
instance.Start();
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//设置运行文件
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//设置启动参数
//startInfo.Arguments = String.Join(" ", Args);
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
//如果不是管理员,则启动UAC
System.Diagnostics.Process.Start(startInfo);
//退出
System.Windows.Forms.Application.Exit();
}
catch
{
}
}*/
//这是不要求管理员权限的版本
if (System.IO.File.Exists(Application.StartupPath + @"\1.txt"))
useSenseShield = true;
if (System.IO.File.Exists(Application.StartupPath + @"\000.txt")) showNsegExtraction = false;
if (useSenseShield)
{
shieldValue.Clear();
try
{
//1.生成目录下需要有4个运行库,分别在x64和x86下,每个里面两个
//2.在C#项目里引用SlmRuntimeCsharp.dll
//3.插入加密狗,执行代码测试
uint[] moduleIds = DogDecrypting.decryptingModules(4/*, moduleIds*/);//第一个参数固定为4
//this.label2.Text = string.Format("加密狗内许可模块号:{0}{1}", Environment.NewLine, string.Join(",", moduleIds));
foreach (uint menuId in moduleIds)
if (!shieldValue.ContainsKey(menuId))
shieldValue.Add(menuId, true);
else
shieldValue[menuId] = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return 0;
}
}
instance = new Startup(args);
instance.ModifySettingPrefix(args);
instance.SystemReset();
instance.InitSetting();
instance.Start();
//if (instance.configModel.StartImgStatus == 2)
//{
// //this.splashForm = new SplashForm();
// SplashForm splashForm = new SplashForm(Startup.instance.configModel.StartImg);
// splashForm.TopMost = true;
// splashForm.Show();
// splashForm.Update();
//}
return 0;
}
///
/// 获取menuId对应的菜单是否显示
///
///
///
public static bool getMenuIdVisible(int menuId)
{
if (shieldValue.ContainsKey((uint)menuId))
return shieldValue[(uint)menuId];
if (!useSenseShield)
return true;
return false;
}
public static bool senseShieldRunLoop()
{
try
{
uint[] moduleIds = DogDecrypting.decryptingModules(4/*, moduleIds*/);//第一个参数固定为4
}
catch (Exception ex)
{
if (!haveShowSenseAlert)
{
haveShowSenseAlert = true;
if (MessageBox.Show(ex.Message, "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
haveShowSenseAlert = false;
}
return false;
}
return true;
}
///
/// 获取menuId对应的菜单是否可点击
///
///
/// 是否显示提示框
///
public static bool getMenuIdUsable(List menuIdlists, bool showAlert = false)
{
if (useSenseShield)
{
try
{
uint[] moduleIds = DogDecrypting.decryptingModules(4/*, moduleIds*/);//第一个参数固定为4
//this.label2.Text = string.Format("加密狗内许可模块号:{0}{1}", Environment.NewLine, string.Join(",", moduleIds));
bool existMenuId = false;
foreach (uint theMenuId in moduleIds)
if (menuIdlists.Contains((int)theMenuId))
{
existMenuId = true;
break;
}
if (!existMenuId && showAlert && !haveShowSenseAlert)
{
haveShowSenseAlert = true;
if (MessageBox.Show("该模块颁发许可未发现", "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
haveShowSenseAlert = false;
}
//haveShowSenseAlert = false;
return existMenuId;
}
catch (Exception ex)
{
if (showAlert && !haveShowSenseAlert)
{
haveShowSenseAlert = true;
if (MessageBox.Show(ex.Message, "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
haveShowSenseAlert = false;
}
//return false;
while (senseShieldRunLoop() == false)
{
System.Threading.Thread.Sleep(20);
}
}
}
return true;
}
///
/// 初始化配置信息
///
private void InitSetting()
{
//App基础配置
//configModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Config.xml", FileMode.Open));
//载物台配置信息
loadingStageModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\LoadingStage.xml", FileMode.Open));
//设置->常规设置->用户信息
userInfo = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\UserInfo.xml", FileMode.Open));
//设置->网格设置
gridModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Grid.xml", FileMode.Open));
//工具->自定义界面-快捷键配置
hotkeyModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Hotkey.xml", FileMode.Open));
//工具->工作流程
workFlowModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\WorkFlow.xml", FileMode.Open));
//工具->自定义界面-快捷栏
shortcutbarModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Shortcutbar.xml", FileMode.Open));
//工具->自定义界面-工具栏
toolbarModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Toolbar.xml", FileMode.Open));
//toolbarLocationModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\ToolbarLocation.xml", FileMode.Open));
//标注样式配置
labelStyleModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Label\\" + configModel.LabelStyle, FileMode.Open));
//测量样式配置
measureStyleModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Measure\\" + configModel.MeasurementStyle, FileMode.Open));
// 设置-常规设置-辅助线样式信息
guideStyleModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\SetUp\\" + "GuideStyle.xml", FileMode.Open)); ;
//水印样式配置
watermarkModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Watermark\\" + configModel.Watermark, FileMode.Open));
// 工字线配置
workTypeStyleModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\WorkType\\" + configModel.WorkType, FileMode.Open));
//标尺样式配置
rulerModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Ruler.xml", FileMode.Open));
//相机参数配置
cameraParamModel = CameraConfigs.GetInstance().GetCurrentCameraParamModel(); // XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\CameraParam\\CameraParam.xml", FileMode.Open));
//工艺图比照配置
artworkModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\ArtworkModel.xml", FileMode.Open));
//电动偏光配置
motorizedLightModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\MotorizedLightModel.xml", FileMode.Open));
//电压配置
voltageModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\VoltageModel.xml", FileMode.Open));
imageMenuModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\ParameterSaving\\ParameterSaving.xml", FileMode.Open));
binaryActionModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\BinaryActionSaving\\ParameterSaving.xml", FileMode.Open));
//初始化提取,DB中保存的的标尺
mic_rulersAll = mic_rulers_BLL.FindAll();
//初始化标尺信息
InitRulerInfo();
//初始化App内的单位
InitUnitInfo();
//初始化单位对应的枚举数字
CompanyEnumeration();
}
///
/// 初始化系统选择的单位的信息
/// 单位对应的枚举数字
///
public void CompanyEnumeration()
{
companyEnume = new Dictionary();
companyEnume.Add(PdnResources.GetString("MeasurementUnit.Inch"), 1);//英寸
companyEnume.Add(PdnResources.GetString("MeasurementUnit.Mil"), 7);//英寸
companyEnume.Add(PdnResources.GetString("Menu.cm.text"), 2);//厘米
companyEnume.Add(PdnResources.GetString("Menu.Mm.text"), 3);//毫米
companyEnume.Add(PdnResources.GetString("Menu.Micron.text"), 4);//微米
companyEnume.Add(PdnResources.GetString("Menu.nanometer.text"), 5);//纳米
companyEnume.Add(PdnResources.GetString("Menu.Pixel.text"), 6);//像素
}
///
/// 初始化系统选择的单位的信息
/// 如果初始安装没有设置过,则默认微米
///
public void InitUnitInfo()
{
if (configModel != null && configModel.Unit > 0)
{
measurementUnit = (MeasurementUnit)Enum.Parse(typeof(MeasurementUnit), configModel.Unit.ToString());
}
else
{
measurementUnit = MeasurementUnit.Micron;
}
}
///
/// 初始化标尺信息,从数据库中读取
/// 然后根据标尺的单位,换算出所有单位的数据
///
public void InitRulerInfo()
{
rules.Clear();
if (configModel != null /*&& configModel.RulerId>0*/)
{
for (int i = 0; i < Startup.instance.mic_rulersAll.Count; i++)
{
if (Startup.instance.mic_rulersAll[i].id == configModel.RulerId)
{
ruleDB = Startup.instance.mic_rulersAll[i];
break;
}
}
//ruleDB = mic_rulers_BLL.FindDefault(configModel.RulerId);
if (ruleDB != null)
{
//计算单位长度 比如0.05英寸/像素; 100纳米/像素;
double unitLength = (double)(ruleDB.physical_length / (decimal)ruleDB.pixel_length);
switch (ruleDB.ruler_units)
{
case (int)MeasurementUnit.Inch://英寸
rules.Add(MeasurementUnit.Inch, unitLength); //英寸
rules.Add(MeasurementUnit.Mil, 1000 * unitLength); //米尔
rules.Add(MeasurementUnit.Centimeter, 2.54 * unitLength); //厘米
rules.Add(MeasurementUnit.Millimeter, 25.4 * unitLength); //毫米
rules.Add(MeasurementUnit.Micron, 25400 * unitLength); //微米
rules.Add(MeasurementUnit.Nano, 25400000 * unitLength); //纳米
break;
case (int)MeasurementUnit.Mil://米尔
rules.Add(MeasurementUnit.Mil, unitLength); //米尔
rules.Add(MeasurementUnit.Inch, 0.001 * unitLength); //英寸
rules.Add(MeasurementUnit.Centimeter, 0.00254 * unitLength); //厘米
rules.Add(MeasurementUnit.Millimeter, 0.0254 * unitLength); //毫米
rules.Add(MeasurementUnit.Micron, 25.4 * unitLength); //微米
rules.Add(MeasurementUnit.Nano, 25400 * unitLength); //纳米
break;
case (int)MeasurementUnit.Centimeter://厘米
rules.Add(MeasurementUnit.Inch, 0.3937008 * unitLength); //英寸
rules.Add(MeasurementUnit.Mil, 393.7008 * unitLength); //米尔
rules.Add(MeasurementUnit.Centimeter, unitLength); //厘米
rules.Add(MeasurementUnit.Millimeter, 10 * unitLength); //毫米
rules.Add(MeasurementUnit.Micron, 10000 * unitLength); //微米
rules.Add(MeasurementUnit.Nano, 10000000 * unitLength); //纳米
break;
case (int)MeasurementUnit.Millimeter://毫米
rules.Add(MeasurementUnit.Inch, 0.0393701 * unitLength); //英寸
rules.Add(MeasurementUnit.Mil, 39.3701 * unitLength); //米尔
rules.Add(MeasurementUnit.Centimeter, 0.1 * unitLength); //厘米
rules.Add(MeasurementUnit.Millimeter, unitLength); //毫米
rules.Add(MeasurementUnit.Micron, 1000 * unitLength); //微米
rules.Add(MeasurementUnit.Nano, 1000000 * unitLength); //纳米
break;
case (int)MeasurementUnit.Micron://微米
rules.Add(MeasurementUnit.Inch, 0.00003937007874 * unitLength); //英寸
rules.Add(MeasurementUnit.Mil, 0.03937007874 * unitLength); //米尔
rules.Add(MeasurementUnit.Centimeter, 0.0001 * unitLength); //厘米
rules.Add(MeasurementUnit.Millimeter, 0.001 * unitLength); //毫米
rules.Add(MeasurementUnit.Micron, unitLength); //微米
rules.Add(MeasurementUnit.Nano, 1000 * unitLength); //纳米
break;
case (int)MeasurementUnit.Nano://纳米
rules.Add(MeasurementUnit.Inch, 3.9370e-8 * unitLength); //英寸
rules.Add(MeasurementUnit.Mil, 3.9370e-5 * unitLength); //米尔
rules.Add(MeasurementUnit.Centimeter, 1e-7 * unitLength); //厘米
rules.Add(MeasurementUnit.Millimeter, 1e-6 * unitLength); //毫米
rules.Add(MeasurementUnit.Micron, 0.001 * unitLength); //微米
rules.Add(MeasurementUnit.Nano, unitLength); //纳米
break;
default:
ruleDB = null;
break;
}
}
}
if (ruleDB == null)
{
//如果没有标尺的时候,默认1微米/像素
rules.Add(MeasurementUnit.Inch, 0.0000394); //英寸
rules.Add(MeasurementUnit.Mil, 0.0394); //米尔
rules.Add(MeasurementUnit.Centimeter, 0.0001); //厘米
rules.Add(MeasurementUnit.Millimeter, 0.001); //毫米
rules.Add(MeasurementUnit.Micron, 1); //微米
rules.Add(MeasurementUnit.Nano, 1000); //纳米
}
//设置文档标尺
Document.defaultDpi = 1 / rules[MeasurementUnit.Inch];
}
///
/// 判断是否根据快捷方式参数修改界面
///
///
///
private bool ModifySettingPrefix(string[] argsArr)
{
if (argsArr.Count() == 2 && (0 == string.Compare(argsArr[0], "/personalConfig", true)))
{
string configName = argsArr[1].Replace("/", "");
if (Directory.Exists(Application.StartupPath + "\\Config\\" + configName + "\\"))
{
this.SettingPrefix = configName;
//MessageBox.Show("配置文件为:" + this.SettingPrefix);
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
//启动动画
public void StartAnimation()
{
if (Startup.instance.configModel.StartImgStatus == 2)
{
//this.splashForm = new SplashForm();
this.splashForm = new SplashForm(Startup.instance.configModel.StartImg);
this.splashForm.TopMost = true;
this.splashForm.StartPosition = FormStartPosition.CenterParent;
this.splashForm.Show();
this.splashForm.Update();
}
}
///
/// 系统复位
///
///
private void SystemReset()
{
//先单独获取App基础配置
configModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Config.xml", FileMode.Open));
MarkPointRect.markPointRectWidth = configModel.MarkpointWidth;
MarkPointRect.MarkpointAreaColor = configModel.MarkpointAreaColor;
MarkPointRect.MarkpointLineColor = configModel.MarkpointLineColor;
MarkPointRect.MarkpointLineWidth = configModel.MarkpointLineWidth;
MarkPointRect.MarkpointStyle = configModel.MarkpointStyle;
PdnResources.Initialize(configModel);
//需要复位
if (configModel.LabelInformationReset == 1 || configModel.MeasurementInformationReset == 1 || configModel.LogReset == 1 ||
configModel.ShortcutBarReset == 1 || configModel.ToolbarReset == 1 || configModel.HotKeyReset == 1)
{
try
{
//标注初始化
if (configModel.LabelInformationReset == 1)
{
string originalFilePath = Application.StartupPath + "\\Config\\Original\\Label\\Default.xml";
string destFilePath = Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Label\\Default.xml";
System.IO.File.Copy(originalFilePath, destFilePath, true);
configModel.LabelInformationReset = 0;
}
//测量初始化
if (configModel.MeasurementInformationReset == 1)
{
string originalFilePath = Application.StartupPath + "\\Config\\Original\\Measure\\Default.xml";
string destFilePath = Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Measure\\Default.xml";
System.IO.File.Copy(originalFilePath, destFilePath, true);
configModel.MeasurementInformationReset = 0;
}
//log初始化
if (configModel.LogReset == 1)
{
//未处理
configModel.LogReset = 0;
}
//快捷栏初始化
if (configModel.ShortcutBarReset == 1)
{
string originalFilePath = Application.StartupPath + "\\Config\\Original\\Shortcutbar.xml";
string destFilePath = Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Shortcutbar.xml";
System.IO.File.Copy(originalFilePath, destFilePath, true);
configModel.ShortcutBarReset = 0;
}
//工具栏初始化
if (configModel.ToolbarReset == 1)
{
string originalFilePath = Application.StartupPath + "\\Config\\Original\\Toolbar.xml";
string destFilePath = Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Toolbar.xml";
System.IO.File.Copy(originalFilePath, destFilePath, true);
configModel.ToolbarReset = 0;
}
//快捷键初始化
if (configModel.HotKeyReset == 1)
{
string originalFilePath = Application.StartupPath + "\\Config\\Original\\Hotkey.xml";
string destFilePath = Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Hotkey.xml";
System.IO.File.Copy(originalFilePath, destFilePath, true);
configModel.HotKeyReset = 0;
}
string configModelXml = XmlSerializeHelper.XmlSerialize(configModel);
FileOperationHelper.WriteStringToFile(configModelXml, Application.StartupPath + "\\Config\\" + SettingPrefix + "\\Config.xml", FileMode.Create);
//MessageBox.Show(PdnResources.GetString("Menu.emresetsuccessfulthesoftw.text"));
}
catch (Exception)
{
MessageBox.Show(PdnResources.GetString("Menu.Systemresetfailure.text"));
}
}
}
public void InitCameraManager()
{
CameraManager.GetInstance();
CameraManager.OnCaptureTimeOut += () =>
{
/*MessageBox.Show("相机采集超时");*/
};
}
///
/// 初始化平台运动控制器
///
public void InitStageController()
{
var m_Stage = AxisController.GetInstance(loadingStageModel.BaseSetType);
if (SerialPort.GetPortNames().Length > 0 || AxisController.ControllerType.Equals("HDS"))
{
m_Stage.LoadingStageModel = instance.loadingStageModel;
m_Stage.Open();
}
}
}
}