202304071142Change

This commit is contained in:
17860779768 2023-04-07 11:42:26 +08:00
parent 129d828728
commit ced0bda28e
26 changed files with 1135 additions and 68 deletions

View File

@ -39,7 +39,7 @@ namespace XKRS.Common.Model.Authority
{ {
AuthorityCheckOperation(); AuthorityCheckOperation();
} }
public static void AuthorityCheckOperation() public static bool AuthorityCheckOperation()
{ {
if (!_isCheckAuthorityNecessary) if (!_isCheckAuthorityNecessary)
{ {

View File

@ -22,5 +22,10 @@ namespace XKRS.Common.Factory
IRunCtrl runCtrl = Activator.CreateInstance(type, new object[] { device }) as IRunCtrl; IRunCtrl runCtrl = Activator.CreateInstance(type, new object[] { device }) as IRunCtrl;
return runCtrl; return runCtrl;
} }
public static bool IsDeviceCtrlExisted(string typeName,EnumHelper.DeviceAttributeType ctrlType)
{
var type = FactoryHelper.GetTypeByAttributeTypeName(typeName, ctrlType);
return type != null;
}
} }
} }

View File

@ -10,7 +10,7 @@ namespace XKRS.Common.Model.Helper
public class DeviceAttribute:Attribute public class DeviceAttribute:Attribute
{ {
/// <summary> /// <summary>
/// 设备类型 /// 设备类型,指示该信息的设备类型,适用于设备信息和配置信息
/// </summary> /// </summary>
public string TypeCode { get; set; } public string TypeCode { get; set; }
@ -20,6 +20,47 @@ namespace XKRS.Common.Model.Helper
/// </summary> /// </summary>
public DeviceAttributeType AttrType { get; set; } public DeviceAttributeType AttrType { get; set; }
} }
/// <summary>
/// 预置状态特性,指定该修饰信息的前置状态允许范围
/// </summary>
public class PreStateAttribute : Attribute
{
public int PreState { get; set; }
public PreStateAttribute(int _preState)
{
PreState = _preState;
}
/// <summary>
/// 检查当前待执行操作的前置状态要求是否合法
/// </summary>
/// <param name="currentState"></param>
/// <returns></returns>
public bool CheckPreStateValid(int currentState)
{
return (currentState & PreState) == currentState;
}
}
public class ColorSelectAttribute : Attribute
{
public string SelectdColor { get; set; }
public ColorSelectAttribute(string selectedColor)
{
SelectdColor = selectedColor;
}
}
public class FontColorSelectAttribute : Attribute
{
public string SelectedColor { get; set; }
public FontColorSelectAttribute(string selectedColor)
{
SelectedColor = selectedColor;
}
}
public class ProcessAttribute : Attribute public class ProcessAttribute : Attribute
{ {

View File

@ -1,17 +1,117 @@
using System; using System;
using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Drawing;
using System.Text; using System.Reflection;
using System.Threading.Tasks;
namespace XKRS.Common.Model.Helper namespace XKRS.Common.Model.Helper
{ {
public static class EnumHelper public static class EnumHelper
{ {
/// <summary>
/// 获取具体某一枚举的中文描述
/// </summary>
/// <param name="enumObj"></param>
/// <returns></returns>
public static string GetEnumDescription(this Enum enumObj)
{
Type t = enumObj.GetType();
FieldInfo f = t.GetField(enumObj.ToString());
if (f == null)
{
return enumObj.ToString();
}
DescriptionAttribute attr = f.GetCustomAttribute<DescriptionAttribute>();
if (attr != null)
{
return attr.Description;
}
else
{
return enumObj.ToString();
}
}
public static System.Drawing.Color GetEnumSelectedColor(this Enum enumObj)
{
Type t = enumObj.GetType();
FieldInfo f = t.GetField(enumObj.ToString());
ColorSelectAttribute attr = f.GetCustomAttribute<ColorSelectAttribute>();
if (attr != null)
{
return System.Drawing.Color.FromName(attr.SelectdColor);
}
else
{
return System.Drawing.Color.Transparent;
}
}
public static System.Drawing.Color GetEnumSelectedFontColor(this Enum enumObj)
{
Type t = enumObj.GetType();
FieldInfo f = t.GetField(enumObj.ToString());
var attr = f.GetCustomAttribute<FontColorSelectAttribute>();
if (attr != null)
{
return System.Drawing.Color.FromName(attr.SelectedColor);
}
else
{
return System.Drawing.Color.Transparent;
}
}
/// <summary>
/// 设备状态定义
/// 未初始化和异常状态无前置状态要求
/// 初始化操作前置状态必须是未初始化、关闭状态、异常状态
/// 打开前置必须是初始化和暂停
/// 关闭前置必须是打开和暂停和异常
/// 暂停前置必须是打开
/// </summary>
public enum DeviceState public enum DeviceState
{ {
TBD = -1,
[ColorSelect("Gray")]
[FontColorSelect("Black")]
[Description("未初始化")]
DSUninit = 1,
[ColorSelect("Gold")]
[FontColorSelect("White")]
[PreState(1 + 2 + 4 + 8 + 32)]
[Description("初始化")]
DSInit = 2,
[ColorSelect("Lime")]
[FontColorSelect("Black")]
[PreState(2 + 4 + 16)]
[Description("运行中")]
DSOpen = 4,
[ColorSelect("Gray")]
[FontColorSelect("White")]
[PreState(1 + 4 + 8 + 16 + 32)]
[Description("关闭")]
DSClose = 8,
[ColorSelect("Gold")]
[FontColorSelect("White")]
[PreState(4 + 16)]
[Description("暂停")]
DSPause = 16,
[ColorSelect("Red")]
[FontColorSelect("White")]
[Description("异常")]
DSExcept = 32
} }
[Flags]//将枚举视为位域 [Flags]//将枚举视为位域
@ -20,7 +120,40 @@ namespace XKRS.Common.Model.Helper
[Description("运行控件")] [Description("运行控件")]
RunCtrl=512, RunCtrl = 512,
}
public enum LogLevel
{
[Description("辅助")]
[ColorSelect("White")]
[FontColorSelect("Blue")]
Assist = 1,
[Description("详细")]
[ColorSelect("White")]
[FontColorSelect("Green")]
Detail = 2,
[Description("信息")]
[ColorSelect("White")]
[FontColorSelect("Dark")]
Information = 3,
[Description("动作")]
[ColorSelect("White")]
[FontColorSelect("Blue")]
Action = 4,
[Description("错误")]
[ColorSelect("White")]
[FontColorSelect("Blue")]
Error = 5,
[Description("警报")]
[ColorSelect("White")]
[FontColorSelect("Blue")]
Warning = 6,
[Description("异常")]
[ColorSelect("White")]
[FontColorSelect("Blue")]
Exception = 7,
} }
} }
} }

View File

@ -0,0 +1,123 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static XKRS.Common.Model.Helper.EnumHelper;
namespace XKRS.Common.Model.Helper
{
public class LoggerHelper
{
public event Action<DateTime, string> OnLogExceptionRaised;
public string LogPath { get; set; }//获取日志地址
public string LogPrefix { get; set; }
LogLevel LogLevel = LogLevel.Information;
public LoggerHelper() { }
public LoggerHelper(string logPath, string logPrefix, LogLevel logLevel = LogLevel.Information)
{
LogPath = logPath;
LogPrefix = logPrefix;
LogLevel = logLevel;
}
public void SetLogLevel(LogLevel logLevel)
{
if (LogLevel != logLevel)
LogLevel = logLevel;
}
//耗时操作从 _taskFactory分配线程
//public TaskFactory _taskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning);
readonly ConcurrentQueue<LogMsg> _logQueue = new ConcurrentQueue<LogMsg>();
Task _logTask = null;
readonly object _logLock = new object();
public async void LogAsync(LogMsg msg)
{
await Task.Run(() =>
{
if (string.IsNullOrEmpty(LogPath) || string.IsNullOrWhiteSpace(LogPath))
{
return;
}
//Enqueue:将对象添加到ConcurrentQueue的结尾处
_logQueue.Enqueue(msg);
lock (_logLock)
{
if (_logTask == null)
{
_logTask = Task.Run(async () =>
{
string filePath = Path.Combine(LogPath, $"{(string.IsNullOrWhiteSpace(LogPrefix) ? "Log_" : ("Log_" + LogPrefix + "_"))}{DateTime.Now.ToString("yyyyMMdd")}.txt");
try
{
if (!StaticHelper.CheckFileCanUse(filePath))
{
OnLogExceptionRaised?.Invoke(DateTime.Now, $"日志文件{filePath}被占用,无法写入");
return;
}
using (StreamWriter writer=new StreamWriter(filePath, true, Encoding.UTF8))
{
while (true)
{
if (!Directory.Exists(LogPath))
{
Directory.CreateDirectory(LogPath);
}
while (_logQueue.Count > 0)
{
//尝试移出并返回并发队列开头处的对象
if(_logQueue.TryDequeue(out LogMsg log))
{
if (log.LogLevel >= LogLevel)
{
//将行结束符的字符串写入文本字符串或流
writer.WriteLine($"{log.LogTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}[{log.ThreadId}]\t{log.LogLevel.GetEnumDescription()}");
}
}
}
writer.Flush();
//delay:创建将在延迟后完成的任务
await Task.Delay(2000);
}
}
}
catch(Exception ex)
{
OnLogExceptionRaised?.Invoke(DateTime.Now, $"日志文件{filePath}写入异常:{ex.GetExceptionMessage()}");
}
});
}
}
});
}
public void LogAsync(DateTime dt,LogLevel logLevel,string msg)
{
LogAsync(new LogMsg(dt, logLevel, msg));
}
}
public class LogMsg
{
public DateTime LogTime { get; set; }
public LogLevel LogLevel { get; set; }
public string Msg { get; set; }
public string MsgSource { get; set; }
public int ThreadId { get; set; }
public LogMsg() { }
public LogMsg(DateTime dt,LogLevel logLevel,string msg)
{
LogTime = dt;
LogLevel = logLevel;
Msg = msg;
}
public override string ToString()
{
return $"{LogTime.ToString("HH:mm:ss.fff")}\t{MsgSource}\t{Msg}";
}
}
}

View File

@ -1,4 +1,5 @@
using System; using Newtonsoft.Json;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@ -13,17 +14,35 @@ namespace XKRS.Common.Model.Helper
//声明一个SettingInfo类型的字段 //声明一个SettingInfo类型的字段
public static SettingInfo SettingInfo; public static SettingInfo SettingInfo;
public static string SettingPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SETTINGFILE); public static string SettingPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SETTINGFILE);
/// <summary>
/// 检查配置文件是否存在且有效
/// </summary>
/// <returns>如果文件存在且配置内容有效返回true否则返回false</returns>
public static bool IsSettingFileValid()
{
if (!File.Exists(SettingPath))
{
return false;
}
return null != SettingInfo;
}
public static void InitWithContent(string content)
{
SettingInfo = JsonConvert.DeserializeObject<SettingInfo>(content);
using(StreamWriter writer=new StreamWriter(SettingPath, false, System.Text.Encoding.UTF8))
{
writer.Write(content);
writer.Flush();
}
}
/// <summary> /// <summary>
/// 声明一个静态方法,获取选择的布局 /// 声明一个静态方法,获取选择的布局
/// </summary> /// </summary>
/// <returns>返回当前布局</returns> /// <returns>返回当前布局</returns>
public static string GetSelectLayout() public static string GetSelectdLayout()
{ {
return SettingInfo.CurrLayout; return SettingInfo.CurrLayout;
} }
@ -89,11 +108,18 @@ namespace XKRS.Common.Model.Helper
} }
return iconPath; return iconPath;
} }
} }
#region
public static void SetCurrLayout(string name)
{
if(SettingInfo.CurrLayout!=name)
}
#endregion
/// <summary> /// <summary>
/// 设置信息类,声明自动属性 /// 设置信息类,声明自动属性
/// </summary> /// </summary>
@ -108,6 +134,7 @@ namespace XKRS.Common.Model.Helper
public string Description { get; set; } public string Description { get; set; }
public string CurrLayout { get; set; } = ""; public string CurrLayout { get; set; } = "";
public bool IsMinimumWhenClose { get; set; } = false;
} }

View File

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace XKRS.Common.Model.Helper
{
public static class StaticHelper
{
#region
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
private const int OF_READWRITE = 2;
private const int OF_SHARE_DENY_NONE = 0x40;
private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 检测文件是否只读或者使用
/// </summary>
/// <param name="fileName"></param>
/// <returns>true可用false在用或只读</returns>
public static bool CheckFileCanUse(string fileName)
{
if (!File.Exists(fileName))
return true;//文件不存在
if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
return false;//文件只读
IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (vHandle == HFILE_ERROR)
{
CloseHandle(vHandle);
return false;//文件被占用
}
CloseHandle(vHandle);//文件没被占用
return true;
}
#endregion
public static List<FileInfo>GetAllFileByFolder(string folderName,string fileFilter,bool isContainSubFolder = false)
{
List<FileInfo> resList = new List<FileInfo>();
try
{
DirectoryInfo currDir = new DirectoryInfo(folderName);//当前目录
FileInfo[] currFiles = currDir.GetFiles(fileFilter);//当前目录文件
foreach (FileInfo file in currFiles)
{
if (fileFilter.ToLower().IndexOf(file.Extension.ToLower()) >= 0)
{
resList.Add(file);
}
}
if (isContainSubFolder)
{
//GetDirectories:返回指定目录中子目录的名称
string[] subFolders = Directory.GetDirectories(folderName);
foreach(string subFolder in subFolders)
{
resList.AddRange(GetAllFileByFolder(subFolder, fileFilter));//递归
}
}
}
catch(Exception ex)
{
throw ex;
}
return resList;
}
}
}

View File

@ -3,12 +3,15 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using XKRS.Common.Model.Helper;
namespace XKRS.Common.Interface namespace XKRS.Common.Interface
{ {
public interface ILogger public interface ILogger
{ {
//event Action<LogMsg> OnLog; event Action<LogMsg> OnLog;
LoggerHelper LoggerHelper { get; set; }
void LogAsync(LogMsg msg);
} }
} }

View File

@ -3,26 +3,38 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using static XKRS.Common.Model.Helper.EnumHelper;
namespace XKRS.Common.Interface namespace XKRS.Common.Interface
{ {
public interface IProcess:ILogger,IExceptionHandler public interface IProcess:ILogger,IExceptionHandler
{ {
#region
/// <summary> /// <summary>
/// 流程使用的硬件设备集合 /// 流程使用的硬件设备集合
/// </summary> /// </summary>
List<IDevice> DeviceCollection { get; set; } List<IDevice> DeviceCollection { get; set; }
#endregion
#region
void Close();
/// <summary> /// <summary>
/// 初始化Process /// 初始化Process
/// </summary> /// </summary>
/// <param name="configPath"></param> /// <param name="configPath"></param>
void InitialProcess(string configPath); void InitialProcess(string configPath);
#endregion
#region
//图像输出事件
event Action<DeviceState> OnProcessStateChanged;
event Action<IWarningSet> OnAlarmRaised;
#endregion
} }

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XKRS.Common.Interface
{
public interface IWarningSetCollection
{
List<IWarningSet> WarningSetCollection { get; set; }
}
public interface IWarningSet
{
string WarningDescription { get; set; }
bool CurrentStatus { get; set; }
string SourceDevice { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XKRS.Common.Interface;
namespace XKRS.Common.Model
{
public class ResetWaringSet:IWarningSet
{
public string WarningDescription { get; set; }
public bool CurrentStatus { get; set; }
public string SourceDevice { get; set; }
}
}

View File

@ -37,6 +37,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config" />
<None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Authority\AuthorityCheck.cs" /> <Compile Include="Authority\AuthorityCheck.cs" />
@ -46,6 +47,8 @@
<Compile Include="Factory\UIFactory.cs" /> <Compile Include="Factory\UIFactory.cs" />
<Compile Include="Helper\AttributeHelper.cs" /> <Compile Include="Helper\AttributeHelper.cs" />
<Compile Include="Helper\EnumHelper.cs" /> <Compile Include="Helper\EnumHelper.cs" />
<Compile Include="Helper\LoggerHelper.cs" />
<Compile Include="Helper\StaticHelper.cs" />
<Compile Include="Interface\IDevice.cs" /> <Compile Include="Interface\IDevice.cs" />
<Compile Include="Interface\IExceptionHandler.cs" /> <Compile Include="Interface\IExceptionHandler.cs" />
<Compile Include="Helper\SettingHelper.cs" /> <Compile Include="Helper\SettingHelper.cs" />
@ -53,13 +56,19 @@
<Compile Include="Interface\IMenuNode.cs" /> <Compile Include="Interface\IMenuNode.cs" />
<Compile Include="Interface\IProcess.cs" /> <Compile Include="Interface\IProcess.cs" />
<Compile Include="Interface\IRunCtrl.cs" /> <Compile Include="Interface\IRunCtrl.cs" />
<Compile Include="Interface\IWarningSetCollection.cs" />
<Compile Include="Model\ResetWaringSet.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="dog_net_windows, Version=1.0.1.28668, Culture=neutral, PublicKeyToken=56120be447701319, processorArchitecture=MSIL"> <Reference Include="dog_net_windows, Version=1.0.1.28668, Culture=neutral, PublicKeyToken=56120be447701319, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\libs\SafetyDog\dog_net_windows.dll</HintPath> <HintPath>..\..\libs\SafetyDog\dog_net_windows.dll</HintPath>
</Reference> </Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Drawing" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net472" />
</packages>

View File

@ -1,6 +1,14 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup> </startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration> </configuration>

View File

@ -36,16 +36,19 @@ namespace XKRS.UI.Main
this.tsslLoginStatus = new System.Windows.Forms.ToolStripStatusLabel(); this.tsslLoginStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.stsStripLayout = new System.Windows.Forms.StatusStrip(); this.stsStripLayout = new System.Windows.Forms.StatusStrip();
this.tssBtnLayout = new System.Windows.Forms.ToolStripSplitButton(); this.tssBtnLayout = new System.Windows.Forms.ToolStripSplitButton();
this.ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tsmiSaveLayout = new System.Windows.Forms.ToolStripMenuItem();
this.ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tsmiResetLayout = new System.Windows.Forms.ToolStripMenuItem();
this.ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tsmiSaveLayoutAs = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.stsStripWarning = new System.Windows.Forms.StatusStrip(); this.stsStripWarning = new System.Windows.Forms.StatusStrip();
this.tsslWarning = new System.Windows.Forms.ToolStripStatusLabel();
this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components); this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
this.ctmsExit = new System.Windows.Forms.ContextMenuStrip(this.components); this.ctmsExit = new System.Windows.Forms.ContextMenuStrip(this.components);
this.tsmiExitProgram = new System.Windows.Forms.ToolStripMenuItem(); this.tsmiExitProgram = new System.Windows.Forms.ToolStripMenuItem();
this.dockPanelMain = new WeifenLuo.WinFormsUI.Docking.DockPanel(); this.dockPanelMain = new WeifenLuo.WinFormsUI.Docking.DockPanel();
this.ststripDevices.SuspendLayout(); this.ststripDevices.SuspendLayout();
this.stsStripLayout.SuspendLayout(); this.stsStripLayout.SuspendLayout();
this.stsStripWarning.SuspendLayout();
this.ctmsExit.SuspendLayout(); this.ctmsExit.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
@ -86,6 +89,7 @@ namespace XKRS.UI.Main
this.tsslLoginStatus.Name = "tsslLoginStatus"; this.tsslLoginStatus.Name = "tsslLoginStatus";
this.tsslLoginStatus.Size = new System.Drawing.Size(44, 20); this.tsslLoginStatus.Size = new System.Drawing.Size(44, 20);
this.tsslLoginStatus.Text = "未登录"; this.tsslLoginStatus.Text = "未登录";
this.tsslLoginStatus.Click += new System.EventHandler(this.tsslLoginStatus_Click);
// //
// stsStripLayout // stsStripLayout
// //
@ -95,7 +99,8 @@ namespace XKRS.UI.Main
this.stsStripLayout.Dock = System.Windows.Forms.DockStyle.None; this.stsStripLayout.Dock = System.Windows.Forms.DockStyle.None;
this.stsStripLayout.GripMargin = new System.Windows.Forms.Padding(0); this.stsStripLayout.GripMargin = new System.Windows.Forms.Padding(0);
this.stsStripLayout.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.stsStripLayout.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tssBtnLayout}); this.tssBtnLayout,
this.toolStripStatusLabel1});
this.stsStripLayout.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow; this.stsStripLayout.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
this.stsStripLayout.Location = new System.Drawing.Point(612, 333); this.stsStripLayout.Location = new System.Drawing.Point(612, 333);
this.stsStripLayout.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0); this.stsStripLayout.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
@ -110,9 +115,9 @@ namespace XKRS.UI.Main
// //
this.tssBtnLayout.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.tssBtnLayout.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.tssBtnLayout.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tssBtnLayout.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenuItem, this.tsmiSaveLayout,
this.ToolStripMenuItem, this.tsmiResetLayout,
this.ToolStripMenuItem}); this.tsmiSaveLayoutAs});
this.tssBtnLayout.ForeColor = System.Drawing.SystemColors.Control; this.tssBtnLayout.ForeColor = System.Drawing.SystemColors.Control;
this.tssBtnLayout.Image = ((System.Drawing.Image)(resources.GetObject("tssBtnLayout.Image"))); this.tssBtnLayout.Image = ((System.Drawing.Image)(resources.GetObject("tssBtnLayout.Image")));
this.tssBtnLayout.ImageTransparentColor = System.Drawing.Color.Magenta; this.tssBtnLayout.ImageTransparentColor = System.Drawing.Color.Magenta;
@ -121,42 +126,60 @@ namespace XKRS.UI.Main
this.tssBtnLayout.Text = "布局配置"; this.tssBtnLayout.Text = "布局配置";
this.tssBtnLayout.TextImageRelation = System.Windows.Forms.TextImageRelation.TextBeforeImage; this.tssBtnLayout.TextImageRelation = System.Windows.Forms.TextImageRelation.TextBeforeImage;
// //
// 保存布局ToolStripMenuItem // tsmiSaveLayout
// //
this.ToolStripMenuItem.Name = "保存布局ToolStripMenuItem"; this.tsmiSaveLayout.Name = "tsmiSaveLayout";
this.ToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.tsmiSaveLayout.Size = new System.Drawing.Size(136, 22);
this.ToolStripMenuItem.Text = "保存布局"; this.tsmiSaveLayout.Text = "保存布局";
// //
// 重置布局ToolStripMenuItem // tsmiResetLayout
// //
this.ToolStripMenuItem.Name = "重置布局ToolStripMenuItem"; this.tsmiResetLayout.Name = "tsmiResetLayout";
this.ToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.tsmiResetLayout.Size = new System.Drawing.Size(136, 22);
this.ToolStripMenuItem.Text = "重置布局"; this.tsmiResetLayout.Text = "重置布局";
// //
// 布局另存为ToolStripMenuItem // tsmiSaveLayoutAs
// //
this.ToolStripMenuItem.Name = "布局另存为ToolStripMenuItem"; this.tsmiSaveLayoutAs.Name = "tsmiSaveLayoutAs";
this.ToolStripMenuItem.Size = new System.Drawing.Size(136, 22); this.tsmiSaveLayoutAs.Size = new System.Drawing.Size(136, 22);
this.ToolStripMenuItem.Text = "布局另存为"; this.tsmiSaveLayoutAs.Text = "布局另存为";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(131, 20);
this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
// //
// stsStripWarning // stsStripWarning
// //
this.stsStripWarning.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.stsStripWarning.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.stsStripWarning.Dock = System.Windows.Forms.DockStyle.None; this.stsStripWarning.Dock = System.Windows.Forms.DockStyle.None;
this.stsStripWarning.Location = new System.Drawing.Point(596, 0); this.stsStripWarning.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsslWarning});
this.stsStripWarning.Location = new System.Drawing.Point(698, 0);
this.stsStripWarning.MinimumSize = new System.Drawing.Size(100, 24); this.stsStripWarning.MinimumSize = new System.Drawing.Size(100, 24);
this.stsStripWarning.Name = "stsStripWarning"; this.stsStripWarning.Name = "stsStripWarning";
this.stsStripWarning.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.stsStripWarning.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.stsStripWarning.Size = new System.Drawing.Size(202, 24); this.stsStripWarning.Size = new System.Drawing.Size(100, 24);
this.stsStripWarning.SizingGrip = false; this.stsStripWarning.SizingGrip = false;
this.stsStripWarning.TabIndex = 11; this.stsStripWarning.TabIndex = 11;
this.stsStripWarning.Text = "statusStrip1"; this.stsStripWarning.Text = "statusStrip1";
// //
// tsslWarning
//
this.tsslWarning.BackColor = System.Drawing.Color.Red;
this.tsslWarning.ForeColor = System.Drawing.SystemColors.Control;
this.tsslWarning.Margin = new System.Windows.Forms.Padding(15, 3, 0, 2);
this.tsslWarning.Name = "tsslWarning";
this.tsslWarning.Size = new System.Drawing.Size(0, 19);
this.tsslWarning.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// notifyIcon // notifyIcon
// //
this.notifyIcon.BalloonTipTitle = "asdasd"; this.notifyIcon.BalloonTipTitle = "asdasd";
this.notifyIcon.ContextMenuStrip = this.ctmsExit; this.notifyIcon.ContextMenuStrip = this.ctmsExit;
this.notifyIcon.Text = "notifyIcon1"; this.notifyIcon.Text = "notifyIcon1";
this.notifyIcon.DoubleClick += new System.EventHandler(this.notifyIcon_DoubleClick);
// //
// ctmsExit // ctmsExit
// //
@ -170,6 +193,7 @@ namespace XKRS.UI.Main
this.tsmiExitProgram.Name = "tsmiExitProgram"; this.tsmiExitProgram.Name = "tsmiExitProgram";
this.tsmiExitProgram.Size = new System.Drawing.Size(124, 22); this.tsmiExitProgram.Size = new System.Drawing.Size(124, 22);
this.tsmiExitProgram.Text = "退出程序"; this.tsmiExitProgram.Text = "退出程序";
this.tsmiExitProgram.Click += new System.EventHandler(this.tsmiExitProgram_Click);
// //
// dockPanelMain // dockPanelMain
// //
@ -201,11 +225,15 @@ namespace XKRS.UI.Main
this.Name = "MainFrm"; this.Name = "MainFrm";
this.Text = "MainFrm"; this.Text = "MainFrm";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainFrm_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainFrm_FormClosed);
this.Load += new System.EventHandler(this.MainFrm_Load); this.Load += new System.EventHandler(this.MainFrm_Load);
this.ststripDevices.ResumeLayout(false); this.ststripDevices.ResumeLayout(false);
this.ststripDevices.PerformLayout(); this.ststripDevices.PerformLayout();
this.stsStripLayout.ResumeLayout(false); this.stsStripLayout.ResumeLayout(false);
this.stsStripLayout.PerformLayout(); this.stsStripLayout.PerformLayout();
this.stsStripWarning.ResumeLayout(false);
this.stsStripWarning.PerformLayout();
this.ctmsExit.ResumeLayout(false); this.ctmsExit.ResumeLayout(false);
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
@ -219,14 +247,16 @@ namespace XKRS.UI.Main
private System.Windows.Forms.ToolStripStatusLabel tsslLoginStatus; private System.Windows.Forms.ToolStripStatusLabel tsslLoginStatus;
private System.Windows.Forms.StatusStrip stsStripLayout; private System.Windows.Forms.StatusStrip stsStripLayout;
private System.Windows.Forms.ToolStripSplitButton tssBtnLayout; private System.Windows.Forms.ToolStripSplitButton tssBtnLayout;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tsmiSaveLayout;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tsmiResetLayout;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tsmiSaveLayoutAs;
private System.Windows.Forms.StatusStrip stsStripWarning; private System.Windows.Forms.StatusStrip stsStripWarning;
private System.Windows.Forms.NotifyIcon notifyIcon; private System.Windows.Forms.NotifyIcon notifyIcon;
private System.Windows.Forms.ContextMenuStrip ctmsExit; private System.Windows.Forms.ContextMenuStrip ctmsExit;
private System.Windows.Forms.ToolStripMenuItem tsmiExitProgram; private System.Windows.Forms.ToolStripMenuItem tsmiExitProgram;
private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanelMain; private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanelMain;
private System.Windows.Forms.ToolStripStatusLabel tsslWarning;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
} }
} }

View File

@ -5,6 +5,7 @@ using System.Data;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -12,6 +13,7 @@ using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking; using WeifenLuo.WinFormsUI.Docking;
using XKRS.Common.Factory; using XKRS.Common.Factory;
using XKRS.Common.Interface; using XKRS.Common.Interface;
using XKRS.Common.Model;
using XKRS.Common.Model.Helper; using XKRS.Common.Model.Helper;
using XKRS.UI.Model.Winform; using XKRS.UI.Model.Winform;
using XKRS.UI.Model.Winform.Helper; using XKRS.UI.Model.Winform.Helper;
@ -38,7 +40,7 @@ namespace XKRS.UI.Main
m_deserializeMenuFrm = new DeserializeDockContent(GetMenuFromPersistString); m_deserializeMenuFrm = new DeserializeDockContent(GetMenuFromPersistString);
m_deserializeDeviceRunFrm = new DeserializeDockContent(GetAllFormPersistString); m_deserializeDeviceRunFrm = new DeserializeDockContent(GetAllFormPersistString);
notifyIcon.Text = SettingHelper.GetProgramDescription(); notifyIcon.Text = Text = SettingHelper.GetProgramDescription();
string iconPath = SettingHelper.GetProgramIcon(); string iconPath = SettingHelper.GetProgramIcon();
if (!string.IsNullOrWhiteSpace(iconPath)) if (!string.IsNullOrWhiteSpace(iconPath))
{ {
@ -49,6 +51,15 @@ namespace XKRS.UI.Main
private void RegisterEvent(MenuFormBase dockFrm) private void RegisterEvent(MenuFormBase dockFrm)
{ {
dockFrm.OnUploadProcess = DockFrm_OnUploadProcess; dockFrm.OnUploadProcess = DockFrm_OnUploadProcess;
dockFrm.OnLogMsgOutput -= DockFrm_OnLogMsgOutput;
dockFrm.OnLogMsgOutput += DockFrm_OnLogMsgOutput;
}
private void DockFrm_OnLogMsgOutput1(LogMsg obj)
{
throw new NotImplementedException();
} }
@ -65,10 +76,39 @@ namespace XKRS.UI.Main
{ {
item.Click += MenuFormItem_Click; item.Click += MenuFormItem_Click;
} }
else
{
item.Click += MenuItem_Click;
}
if (parentMenuCode == "")
{
menuMain.Items.Add(item);
}
else
{
ToolStripMenuItem parentNode = GetMatchNode(menuMain.Items, parentMenuCode);
if (parentNode != null)
{
parentNode.DropDownItems.Add(item);
}
}
InitialMenu(menuFrmTypeDict, m.MenuCode);
}); });
} }
private void LogDisplay(LogMsg msg)
{
foreach (var dock in dockPanelMain.Contents)
{
(dock as MenuFormBase)?.LogDisplay(msg);
}
}
internal void DockFrm_OnLogMsgOutput(LogMsg msg)
{
_process?.LogAsync(msg);
}
private async void DockFrm_OnUploadProcess(string frmId, IProcess process) private async void DockFrm_OnUploadProcess(string frmId, IProcess process)
{ {
await Task.Run(() => await Task.Run(() =>
@ -77,7 +117,10 @@ namespace XKRS.UI.Main
this.Invoke(new Action(() => this.Invoke(new Action(() =>
{ {
_process = process; _process = process;
_process.OnLog -= LogDisplay;
_process.OnLog += LogDisplay;
_process.OnAlarmRaised -= Process_OnAlarmUpdate;
_process.OnAlarmRaised += Process_OnAlarmUpdate;
CloseAllDeviceFrm(); CloseAllDeviceFrm();
try try
@ -99,8 +142,106 @@ namespace XKRS.UI.Main
}); });
} }
static object _alarmMsgLock = new object();
List<IWarningSet> _wsList = new List<IWarningSet>();
private async void Process_OnAlarmUpdate(IWarningSet warningSet)
{
this.Invoke(new Action(() =>
{
lock (_alarmMsgLock)
{
if (warningSet is ResetWaringSet)
{
_wsList.Clear();
}
else
{
var existed = _wsList.FirstOrDefault(u => u.SourceDevice == warningSet.SourceDevice && u.WarningDescription == warningSet.WarningDescription);
if (warningSet.CurrentStatus)
{
if (existed == null)
{
_wsList.Add(warningSet);
}
}
else
{
if (existed != null)
{
_wsList.Remove(existed);
}
}
}
tsslWarning.Text = string.Join("\r\n", _wsList.Select(u => u.WarningDescription));
}
}));
await Task.Delay(100);
}
/// <summary>
/// 获取匹配节点
/// </summary>
/// <param name="items"></param>
/// <param name="parentMenuCode"></param>
/// <returns></returns>
private ToolStripMenuItem GetMatchNode(ToolStripItemCollection items, string parentMenuCode)
{
foreach (ToolStripMenuItem node in items)
{
if (node.Tag != null && node.Tag.ToString() == parentMenuCode)
{
return node;
}
else
{
if (node.DropDownItems.Count > 0)
{
var nextNode = GetMatchNode(node.DropDownItems, parentMenuCode);
if (nextNode != null)
{
return nextNode;
}
}
}
}
return null;
}
/// <summary>
/// 不带窗口的菜单项点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MenuItem_Click(object sender, EventArgs e)
{
try
{
SuspendLayout();
ToolStripMenuItem item = sender as ToolStripMenuItem;
bool isExisted = false;
if (isExisted)
{
ResumeLayout();
return;
}
}
catch (Exception ex)
{
LogDisplay(new LogMsg(DateTime.Now, EnumHelper.LogLevel.Warning, ex.Message));
}
}
/// <summary>
/// 带窗口的菜单项点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MenuFormItem_Click(object sender, EventArgs e) private void MenuFormItem_Click(object sender, EventArgs e)
{ {
try try
@ -141,10 +282,14 @@ namespace XKRS.UI.Main
RegisterEvent(dockFrm); RegisterEvent(dockFrm);
ResumeLayout(); ResumeLayout();
if (_process != null)
{
dockFrm.DownloadProcess(_process);
}
} }
catch catch (Exception ex)
{ {
LogDisplay(new LogMsg(DateTime.Now, EnumHelper.LogLevel.Warning, ex.Message));
} }
} }
#endregion #endregion
@ -160,7 +305,7 @@ namespace XKRS.UI.Main
LoadProcess(); LoadProcess();
LoadLayoutFromXML(m_deserializeDeviceRunFrm); LoadLayoutFromXML(m_deserializeDeviceRunFrm);
LoadProcess(false); LoadProcess(false);
Openexe(); //Openexe();
} }
private void Openexe() private void Openexe()
@ -258,9 +403,24 @@ namespace XKRS.UI.Main
} }
_process.InitialProcess(""); _process.InitialProcess("");
} }
else
{
_process.OnLog -= LogDisplay;
_process.OnLog += LogDisplay;
_process.OnAlarmRaised -= Process_OnAlarmUpdate;
_process.OnAlarmRaised += Process_OnAlarmUpdate;
_process.OnProcessStateChanged -= _process_OnProcessStateChanged;
_process.OnProcessStateChanged += _process_OnProcessStateChanged;
}
}
private void _process_OnProcessStateChanged(EnumHelper.DeviceState obj)
{
this.Invoke(new Action(() =>
{
notifyIcon.Text = Text = $"{SettingHelper.GetProgramDescription()}{obj.GetEnumDescription()}";
}));
} }
#region Login #region Login
bool isLogin = false; bool isLogin = false;
@ -281,6 +441,11 @@ namespace XKRS.UI.Main
} }
} }
} }
private void tsslLoginStatus_Click(object sender, EventArgs e)
{
AdvancedPwdFrm pwdFrm = new AdvancedPwdFrm();
pwdFrm.ShowDialog();
}
private void OnLoginOK(bool isLogin) private void OnLoginOK(bool isLogin)
{ {
@ -326,20 +491,216 @@ namespace XKRS.UI.Main
})); }));
} }
private void CloseAllDocuments()
{
try
{
_process?.Close();
}
catch (Exception)
{
}
foreach (var dock in dockPanelMain.Contents.ToList())
{
(dock as Form).Close();
}
}
private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!SettingHelper.SettingInfo.IsMinimumWhenClose || _isExit)
{
if (MessageBox.Show("是否确认关闭当前程序?", "关闭提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
{
e.Cancel = true;
return;
}
notifyIcon.Dispose();
CloseAllDeviceFrm();
}
else
{
e.Cancel = true;
notifyIcon.ShowBalloonTip(5000, "后台消息", "程序转换到后台运行,双击图标再次打开程序界面!", ToolTipIcon.Info);
this.WindowState = FormWindowState.Minimized;
this.Visible = false;
}
}
bool _isExit = false;
private void tsmiExitProgram_Click(object sender, EventArgs e)
{
notifyIcon.Dispose();
CloseAllDocuments();
_isExit = true;
this.Close();
}
private void MainFrm_FormClosed(object sender, FormClosedEventArgs e)
{
Environment.Exit(0);
}
private void notifyIcon_DoubleClick(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Maximized;
}
#endregion
#region Device Display
readonly Dictionary<string, DeviceRunFrmBase> showedDeviceUIDict = new Dictionary<string, DeviceRunFrmBase>();
private void LoadDevices()
{
while (ststripDevices.Items.Count > 1)
{
ststripDevices.Items.RemoveAt(1);
}
ststripDevices.Invalidate();
_process.DeviceCollection.ForEach(dev =>
{
ToolStripStatusLabel tssl = new ToolStripStatusLabel(dev.Name);
tssl.ForeColor = SystemColors.Control;
tssl.DoubleClickEnabled = true;
tssl.DoubleClick += Tssl_DoubleClick;
tssl.MouseHover += Tssl_MouseHover;
tssl.MouseLeave += Tssl_MouseLeave;
dev.OnDeviceStateChanged += Device_OnDeviceStateChanged;
tssl.Tag = dev;
ststripDevices.Items.Add(tssl);
});
}
private void Tssl_MouseLeave(object sender, EventArgs e)
{
this.Cursor = Cursors.Default;
}
private void Tssl_MouseHover(object sender, EventArgs e)
{
if (sender is ToolStripStatusLabel lbl)
{
this.Cursor = Cursors.Hand;
}
}
private void Tssl_DoubleClick(object sender, EventArgs e)
{
if ((sender as ToolStripStatusLabel).Tag is IDevice device)
{
string typeCode = device.GetType().GetCustomAttribute<DeviceAttribute>()?.TypeCode;
if (!string.IsNullOrWhiteSpace(typeCode))
{
if (UIFactory.IsDeviceCtrlExisted(typeCode, EnumHelper.DeviceAttributeType.RunCtrl))
{
//确定是否是否包含指定的键
if (!showedDeviceUIDict.ContainsKey(device.Id))
{
var runCtrl = UIFactory.GetRunCtrl(device);
DeviceRunFrmBase runFrm = new DeviceRunFrmBase(device, runCtrl);
runFrm.Text = device.Name;
runFrm.MdiParent = this;
runFrm.DockPanel = dockPanelMain;
runFrm.DockState = DockState.Document;
runFrm.FormClosed += DeviceDisplayFrm_FormClosed;
runFrm.DockStateChanged += DockStateChanged;
showedDeviceUIDict[device.Id] = runFrm;
}
else
{
//将控件带到Z顺序前面
showedDeviceUIDict[device.Id].BringToFront();
}
}
}
}
}
private void Device_OnDeviceStateChanged(IDevice device, EnumHelper.DeviceState currentState)
{
ststripDevices.BeginInvoke(new Action(() =>
{
Console.WriteLine();
for (int i = 1; i < ststripDevices.Items.Count; i++)
{
if ((ststripDevices.Items[i].Tag as IDevice)?.Id == device.Id)
{
ststripDevices.Items[i].BackColor = currentState.GetEnumSelectedColor();
ststripDevices.Items[i].ForeColor = currentState.GetEnumSelectedFontColor();
break;
}
}
}));
}
#endregion #endregion
#region Layout布局 #region Layout布局
List<IDockContent> _dockContentList = new List<IDockContent>();
string _layoutFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{SettingHelper.GetSelectLayout()}.layout");//路径 string _layoutFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{SettingHelper.GetSelectdLayout()}.layout");//路径
private DeserializeDockContent m_deserializeMenuFrm; private DeserializeDockContent m_deserializeMenuFrm;
private DeserializeDockContent m_deserializeDeviceRunFrm; private DeserializeDockContent m_deserializeDeviceRunFrm;
private void LoadLayoutMenu()
{
var checkedLayout = SettingHelper.GetSelectdLayout();
//1.获取所有layout文件
var fileNameList = StaticHelper.GetAllFileByFolder(Path.Combine(AppDomain.CurrentDomain.BaseDirectory), "*.layout").Select(u => u.Name).ToList();
var clesrCount = tssBtnLayout.DropDownItems.Count;
for (int i = 0; i < clesrCount - 4; i++)
{
tssBtnLayout.DropDownItems.RemoveAt(0);
}
//2.加载到主menu
fileNameList.ForEach(fileName =>
{
ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem();
toolStripMenuItem.Text = Path.GetFileNameWithoutExtension(fileName);
toolStripMenuItem.Name = fileName;
toolStripMenuItem.Checked = toolStripMenuItem.Text == checkedLayout.ToLower();
toolStripMenuItem.Click += ToolStripMenuItem_Click;
tssBtnLayout.DropDownItems.Insert(0, toolStripMenuItem);
});
}
private void ToolStripMenuItem_Click(object sender,EventArgs e)
{
LoadLayoutFromXML(m_deserializeMenuFrm);
var menuItem = sender as ToolStripMenuItem;
foreach(var menu in tssBtnLayout.DropDownItems)
{
if(menu is ToolStripMenuItem item&& item.Name.Contains(".layout"))
{
item.Checked = false;
if (item.Text.ToLower() == menuItem.Text.ToLower())
{
item.Checked = true;
SettingHelper.SetCurrLayout()
}
}
}
}
private IDockContent GetMenuFromPersistString(string persistString) private IDockContent GetMenuFromPersistString(string persistString)
{ {
//StartWith:确定此字符串的实例的开头是否与指定的字符串匹配
if (persistString.StartsWith("MenuFrm"))
{
var desc = persistString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string menuCode = desc[1];
foreach (var dock in dockPanelMain.Contents)
{
MenuFormBase menu = dock as MenuFormBase;
if (menu != null && menu.Tag.ToString() == menuCode)
{
return dock;
}
}
MenuFormBase dockFrm = MenuFormFactory.GetMenuFrm(menuCode);
if (dockFrm == null)
return null;
dockFrm.Text = desc[2];
dockFrm.SetLoginStatus(IsLogin);
RegisterEvent(dockFrm);
return dockFrm;
}
return null; return null;
} }
private IDockContent GetAllFormPersistString(string persistString) private IDockContent GetAllFormPersistString(string persistString)
@ -348,7 +709,7 @@ namespace XKRS.UI.Main
{ {
var desc = persistString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var desc = persistString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string menuCode = desc[1]; string menuCode = desc[1];
foreach(var dock in dockPanelMain.Contents) foreach (var dock in dockPanelMain.Contents)
{ {
MenuFormBase menu = dock as MenuFormBase; MenuFormBase menu = dock as MenuFormBase;
if (menu != null && menu.Tag.ToString() == menuCode) if (menu != null && menu.Tag.ToString() == menuCode)
@ -425,14 +786,5 @@ namespace XKRS.UI.Main
dockPanelMain.ResumeLayout(true, true); dockPanelMain.ResumeLayout(true, true);
} }
#endregion #endregion
#region Device Display
readonly Dictionary<string, DeviceRunFrmBase> showedDeviceUIDict = new Dictionary<string, DeviceRunFrmBase>();
#endregion
} }
} }

View File

@ -0,0 +1,40 @@

namespace XKRS.UI.Main.MenuForms
{
partial class FrmConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "FrmConfig";
}
#endregion
}
}

View File

@ -0,0 +1,20 @@
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 XKRS.UI.Main.MenuForms
{
public partial class FrmConfig : Form
{
public FrmConfig()
{
InitializeComponent();
}
}
}

View File

@ -1,15 +1,19 @@
using Microsoft.Win32; using Microsoft.Win32;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using XKRS.Common.Model.Authority; using XKRS.Common.Model.Authority;
using XKRS.Common.Model.Helper;
namespace XKRS.UI.Main namespace XKRS.UI.Main
{ {
static class Program static class Program
{ {
static MainFrm mainFrm = null;
/// <summary> /// <summary>
/// 应用程序的主入口点。 /// 应用程序的主入口点。
/// </summary> /// </summary>
@ -17,12 +21,58 @@ namespace XKRS.UI.Main
static void Main() static void Main()
{ {
AutoStart(true); AutoStart(true);
if(AuthorityCheck) if (AuthorityCheck.AuthorityCheckOperation())
{
MessageBox.Show("加密狗本地检测和远程检测失败!请本地插入加密狗或确认远程加密服务就绪。");
//Environment:提供有关当前环境和平台的信息以及操作他们的方法
//Exit:终止此进程,并将退出代码返回到操作系统
Environment.Exit(1);
}
//3f0d870f-0fcc-4f0b-9836-123a679d8bc
if (!HslCommunication.Authorization.SetAuthorizationCode("f562cc4c-4772-4b32-bdcd-f3e122c534e3"))
{
MessageBox.Show("软件授权失败,系统关闭!");
Environment.Exit(1);
}
bool isAppRunning = false;
//Mutex:可用于进程间同步的同步基元
Mutex mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName, out isAppRunning);
if (!isAppRunning)
{
MessageBox.Show("程序已运行,不能再次打开!");
Environment.Exit(1);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainFrm()); //如果没有配置文件,则初始化示例数据
if (!SettingHelper.IsSettingFileValid())
{
SampleHelper.Init();
}
Application.EnableVisualStyles();
//PriorityClass:获取或设置关联进程的总体优先级类别
//ProcessPriorityClass指定系统将与进程关联的优先级
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
//UnhandledException当某个异常未被捕获时出现
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;
mainFrm = new MainFrm();
Application.Run(mainFrm);
AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
Application.ThreadException -= Application_ThreadException;
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
throw new NotImplementedException();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
throw new NotImplementedException();
} }
private static void AutoStart(bool isAuto = true) private static void AutoStart(bool isAuto = true)

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XKRS.Common.Model.Helper;
namespace XKRS.UI.Main
{
public static class SampleHelper
{
/// <summary>
/// 初始化配置数据
/// </summary>
public static void Init()
{
bool settingChecked = false;
while (!settingChecked)
{
if (settingChecked)
{
Environment.Exit(1);
}
//设置目录
string myDoc = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var retPath = Path.Combine(myDoc, "A020");
//将配置文件写入文件
string defaultSetting = "{\"ProcessCodes\":[],\"ProductionCodes\":[\"Default\"],\"DefaultProcess\":\"A020\",\"DefaultProduction\":\"\",\"ConfigPath\":\""
+Path.Combine(retPath, "Configs").Replace("\\", "\\\\")
+ "\",\"Description\":\"振动盘供料缺陷检测系统\",\"IconPath\":null,\"CurrLayout\":\"Default\",\"IsMinimumWhenClose\":false}";
SettingHelper.InitWithContent(defaultSetting);
}
}
}
}

View File

@ -35,6 +35,12 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="HslCommunication, Version=10.6.1.0, Culture=neutral, PublicKeyToken=3d72ad3b6b5ec0e3, processorArchitecture=MSIL">
<HintPath>..\..\packages\HslCommunication.10.6.1\lib\net451\HslCommunication.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Configuration" /> <Reference Include="System.Configuration" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
@ -67,8 +73,15 @@
<Compile Include="MainFrm.Designer.cs"> <Compile Include="MainFrm.Designer.cs">
<DependentUpon>MainFrm.cs</DependentUpon> <DependentUpon>MainFrm.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="MenuForms\FrmConfig.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="MenuForms\FrmConfig.Designer.cs">
<DependentUpon>FrmConfig.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SampleHelper.cs" />
<EmbeddedResource Include="AdvancedPwdFrm.resx"> <EmbeddedResource Include="AdvancedPwdFrm.resx">
<DependentUpon>AdvancedPwdFrm.cs</DependentUpon> <DependentUpon>AdvancedPwdFrm.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>

View File

@ -2,4 +2,6 @@
<packages> <packages>
<package id="DockPanelSuite" version="3.1.0" targetFramework="net472" /> <package id="DockPanelSuite" version="3.1.0" targetFramework="net472" />
<package id="DockPanelSuite.ThemeVS2015" version="3.1.0" targetFramework="net472" /> <package id="DockPanelSuite.ThemeVS2015" version="3.1.0" targetFramework="net472" />
<package id="HslCommunication" version="10.6.1" targetFramework="net472" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net472" />
</packages> </packages>

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using WeifenLuo.WinFormsUI.Docking;
namespace XKRS.UI.Model.Winform namespace XKRS.UI.Model.Winform
{ {
@ -20,4 +21,15 @@ namespace XKRS.UI.Model.Winform
/// </summary> /// </summary>
public bool IsActualForm { get; set; } public bool IsActualForm { get; set; }
} }
public class DockOptionAttribute : Attribute
{
public DockState DockState { get; set; }
public DockOptionAttribute(DockState dockState,int defaultWidth,int defaultHeight)
{
}
}
} }

View File

@ -4,17 +4,21 @@ using System.ComponentModel;
using System.Data; using System.Data;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking; using WeifenLuo.WinFormsUI.Docking;
using XKRS.Common.Interface; using XKRS.Common.Interface;
using XKRS.Common.Model.Helper;
namespace XKRS.UI.Model.Winform namespace XKRS.UI.Model.Winform
{ {
public partial class MenuFormBase : DockContent public partial class MenuFormBase : DockContent
{ {
public Action<string,IProcess> OnUploadProcess { get; set; } public Action<string,IProcess> OnUploadProcess { get; set; }
public event Action<LogMsg> OnLogMsgOutput;
public event Action<bool> OnShowWaitingBar;
public event Action<bool> OnIsLoginChanged; public event Action<bool> OnIsLoginChanged;
public string Id { get; set; } = Guid.NewGuid().ToString(); public string Id { get; set; } = Guid.NewGuid().ToString();
@ -36,6 +40,17 @@ namespace XKRS.UI.Model.Winform
public MenuFormBase() public MenuFormBase()
{ {
InitializeComponent(); InitializeComponent();
KeyPreview = true;
var dockAttr = GetType().GetCustomAttribute<DockOptionAttribute>();
if (dockAttr != null)
{
FormClosing += MenuFormBase_FormClosing;
}
}
private void MenuFormBase_FormClosing(object sender, FormClosingEventArgs e)
{
throw new NotImplementedException();
} }
#region IProcessObserver #region IProcessObserver
@ -48,6 +63,11 @@ namespace XKRS.UI.Model.Winform
#endregion #endregion
#region ILogOutput
public virtual void LogDisplay(LogMsg msg) { }
#endregion
#region Login #region Login

View File

@ -49,6 +49,9 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Configuration" /> <Reference Include="System.Configuration" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="DockPanelSuite" version="3.1.0" targetFramework="net472" /> <package id="DockPanelSuite" version="3.1.0" targetFramework="net472" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net472" />
</packages> </packages>