using JinYuan.ControlLib; using JinYuan.Helper; using JinYuan.MES.Models; using JinYuan.Models; using JinYuan.VirtualDataLibrary; using Language; using Microsoft.Win32; using MiniExcelLibs; using JinYuan.ControlCenters; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Eventing.Reader; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LargeSquareOne { public partial class FrmSystemSet : MultiLanguageForm { private string devPath = string.Empty; private string PlcConfigFilePath = "Device.xlsx"; private string FdConfigFilePath = "fd_config.xlsx"; private List plcConfigs; private List fdConfigs; private string PlcCommunicationConfigPath; private string variableConfigPath; private List PLCTypes = new List(); private bool isEditing = false; private List GradeTypes = new List(); private bool isFDEditing = false; private int editingRowIndex = -1; private int editingFDRowIndex = -1; private readonly string configFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config"); public FrmSystemSet(string devPath) { InitializeComponent(); if (!Directory.Exists(configFolderPath)) Directory.CreateDirectory(configFolderPath); //设置控件样式,去除缓冲 this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.Selectable, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); PlcConfigFilePath = CommonMethods.deviceConfigPath;//Path.Combine(configFolderPath, "Device.xlsx"); FdConfigFilePath = Path.Combine(configFolderPath, "FdConfig.xlsx"); PlcCommunicationConfigPath = CommonMethods.groupConfigPath; //Path.Combine(configFolderPath, $"Group_{CommonMethods.sysConfig.StationNo}.xlsx"); variableConfigPath = CommonMethods.variableConfigPath; // Path.Combine(configFolderPath, $"Variable_{CommonMethods.sysConfig.StationNo}.xlsx"); PLCTypes.AddRange(new string[] { "OmronFinsTCP", "OmronCipNet" }); //var validGradeKeys = MesConfig.GetGrades(); //if (validGradeKeys != null && validGradeKeys.Any()) //{ // GradeTypes.AddRange(validGradeKeys); // GradeTypes.Add("不设置"); // GradeTypes.Add("NG"); //} LoadFDGradeTypesFromGlobal(); // 如果全局还没有数据,从文件加载 if (GradeTypes == null || GradeTypes.Count == 0) { GradeTypes.AddRange(new string[] { "不设置", "NG" }); } SetupDataGridView(); SetupFDDataGridView(); LoadPLCConfig(); LoadFDConfig(); this.tog_AutoStart.IsChecked = CommonMethods.sysConfig.AutoStart; this.tog_AutoLogin.IsChecked = CommonMethods.sysConfig.AutoLogin; this.tog_AutoLock.IsChecked = CommonMethods.sysConfig.AutoLock; this.up_LockPeriod.CurrentValue = CommonMethods.sysConfig.LockPeriod; this.tog_AutoQieHuanM.IsChecked = CommonMethods.sysConfig.AutoQieHuanM; this.up_QieHuanPeriod.CurrentValue = CommonMethods.sysConfig.QieHuanMPeriod; this.up_ShowSeriesCount.CurrentValue = CommonMethods.sysConfig.ShowSeriesCount; this.tog_IsDebugMode.IsChecked = CommonMethods.sysConfig.IsDebugMode; this.tog_SwipeCardMode.IsChecked = CommonMethods.sysConfig.SwipeCardMode; this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching; this.tog_finishSwitch.IsChecked = CommonMethods.sysConfig.FinishSwitching; this.tog_GetMesParam.IsChecked = CommonMethods.sysConfig.GetMesParam; this.tog_SaveThreadTime.IsChecked = CommonMethods.sysConfig.SaveThreadTime; this.tog_Wuliu.IsChecked = CommonMethods.sysConfig.WuLiu; this.txt_equipNo.Text = CommonMethods.sysConfig.GongWei; this.tog_AutoStart.CheckedChanged += new System.EventHandler(this.tog_AutoStart_CheckedChanged); this.tog_AutoLogin.CheckedChanged += new System.EventHandler(this.tog_AutoLogin_CheckedChanged); this.tog_AutoLock.CheckedChanged += new System.EventHandler(this.tog_AutoLock_CheckedChanged); this.up_LockPeriod.ValueChanged += new System.EventHandler(this.up_LockPeriod_ValueChanged); this.tog_Wuliu.CheckedChanged += new System.EventHandler(this.tog_Wuliu_CheckedChanged); this.tog_AutoQieHuanM.CheckedChanged += new System.EventHandler(this.tog_AutoQieHuanM_CheckedChanged); this.up_QieHuanPeriod.ValueChanged += new System.EventHandler(this.up_QieHuanPeriod_ValueChanged); this.up_ShowSeriesCount.ValueChanged += new System.EventHandler(this.up_ShowSeriesCount_ValueChanged); this.txtFactory_code.Text = CommonMethods.mesConfig.siteCode; this.txtline_No.Text = CommonMethods.mesConfig.lineCode; this.txtEqp_code.Text = CommonMethods.mesConfig.equipNum; this.txtBox_materialCode.Text = CommonMethods.mesConfig.MaterialCode; //this.txtGradeSetting.Text = string.Join(",", CommonMethods.mesConfig.grades); this.upDown_layer.CurrentValue = CommonMethods.mesConfig.packLayers; this.upDown_row.CurrentValue = CommonMethods.mesConfig.rowsPerLayer; this.upDown_Col.CurrentValue = CommonMethods.mesConfig.colsPerLayer; this.txtEmployeeAuthCheck.Text = CommonMethods.mesConfig.EmployeeAuthCheck; this.txtDeviceParamRequest.Text = CommonMethods.mesConfig.DeviceParamRequest; this.txtDeviceParamChange.Text = CommonMethods.mesConfig.DeviceParamChange; this.txtQueryTray.Text = CommonMethods.mesConfig.queryTrayUrl; this.txtQueryGrade.Text = CommonMethods.mesConfig.queryGradeUrl; this.txtUpResultParam.Text = CommonMethods.mesConfig.upResultParamUrl; this.txtUnbind.Text = CommonMethods.mesConfig.unbindTrayUrl; this.txtPack.Text = CommonMethods.mesConfig.packLoadUrl; this.txtBox_finishedBattery.Text = CommonMethods.mesConfig.finishedPackUrl; this.txtDeviceAlarm.Text = CommonMethods.mesConfig.DeviceAlarm; this.txtDeviceStatus.Text = CommonMethods.mesConfig.DeviceStatus; this.txtEnergyConsumption.Text = CommonMethods.mesConfig.EnergyConsumption; this.txtAnemometer.Text = CommonMethods.mesConfig.Anemometer; this.txtFactory_code.Text = CommonMethods.mesConfig.siteCode; this.txtline_No.Text = CommonMethods.mesConfig.lineCode; this.txtEqp_code.Text = CommonMethods.mesConfig.equipNum; this.txtCustomerPartNum.Text = CommonMethods.mesConfig.CustomerPartNum; this.txtAppID.Text = CommonMethods.mesConfig.AppID; this.txtAppKey.Text = CommonMethods.mesConfig.AppKey; this.txtGetToken.Text = CommonMethods.mesConfig.GetTokenUrl; FDConfigForm.OnFDConfigChanged += FDConfigForm_OnFDConfigChanged; } /// /// 初始化DataGrid /// private void SetupDataGridView() { // 设置基本属性 dgvPlcConfigs.AutoGenerateColumns = false; dgvPlcConfigs.MultiSelect = false; // 添加数据列 dgvPlcConfigs.Columns.AddRange(new DataGridViewColumn[] { new DataGridViewTextBoxColumn { Name = "PlcNum", HeaderText = "PLC编号", DataPropertyName = "PlcNum", ReadOnly = true, Width = 80, ValueType = typeof(int) }, new DataGridViewComboBoxColumn { Name = "PLCType", HeaderText = "PLC类型", DataPropertyName = "PLCType", DataSource = new List(PLCTypes), // 使用新列表避免引用问题 Width = 160, ValueType = typeof(string), FlatStyle = FlatStyle.Flat, DefaultCellStyle = new DataGridViewCellStyle { BackColor = Color.FromArgb(14, 23, 38), // 深色背景 ForeColor = Color.White, // 白色文字 SelectionBackColor = Color.FromArgb(0, 122, 204), // 选中时的背景色 SelectionForeColor = Color.White, // 选中时的文字颜色 Font = new Font("微软雅黑", 9F) // 字体设置 } }, new DataGridViewTextBoxColumn { Name = "IPAddress", HeaderText = "IP地址", DataPropertyName = "IPAddress", Width = 120, ValueType = typeof(string) }, new DataGridViewTextBoxColumn { Name = "Port", HeaderText = "端口号", DataPropertyName = "Port", Width = 80, ValueType = typeof(string) }, new DataGridViewTextBoxColumn { Name = "HeartBeat", HeaderText = "心跳地址", DataPropertyName = "HeartBeat", Width = 100, ValueType = typeof(string) }, new DataGridViewCheckBoxColumn { Name = "IsHeartBeat", HeaderText = "心跳状态", DataPropertyName = "IsHeartBeat", Width = 80, ValueType = typeof(bool), TrueValue = true, FalseValue = false }, new DataGridViewCheckBoxColumn { Name = "IsActive", HeaderText = "激活状态", DataPropertyName = "IsActive", Width = 80, ValueType = typeof(bool), TrueValue = true, FalseValue = false }, new DataGridViewTextBoxColumn { Name = "Remark", HeaderText = "备注", DataPropertyName = "Remark", Width = 150, ValueType = typeof(string) }, new DataGridViewButtonColumn { Name = "Edit", HeaderText = "操作", Text = "修改".Translated(), UseColumnTextForButtonValue = true, Width = 80 }, new DataGridViewButtonColumn { Name = "Delete", HeaderText = "", Text = "删除".Translated(), UseColumnTextForButtonValue = true, Width = 80 }, new DataGridViewButtonColumn { Name = "CommConfig", HeaderText = "设置", Text = "通信组".Translated(), UseColumnTextForButtonValue = true, Width = 80 }, new DataGridViewButtonColumn { Name = "VariableConfig", HeaderText = "", Text = "变量".Translated(), UseColumnTextForButtonValue = true, Width = 80 }, }); // 设置列为只读 SetColumnsReadOnly(false); // 绑定事件 dgvPlcConfigs.CellClick += DgvPlcConfigs_CellClick; dgvPlcConfigs.CellValidating += DgvPlcConfigs_CellValidating; dgvPlcConfigs.CellValueChanged += DgvPlcConfigs_CellValueChanged; dgvPlcConfigs.DataError += DgvPlcConfigs_DataError; // 设置自动调整行高 dgvPlcConfigs.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; dgvPlcConfigs.RowHeadersVisible = false; } private void SetColumnsReadOnly(bool readOnly) { foreach (DataGridViewColumn col in dgvPlcConfigs.Columns) { // PlcNum 列始终保持只读 if (col.Name == "PlcNum") { col.ReadOnly = true; continue; } // 按钮列不需要设置 ReadOnly 属性 if (col is DataGridViewButtonColumn) continue; // 其他列根据参数设置 col.ReadOnly = readOnly; } } private void SetColumnsFDReadOnly(bool readOnly) { foreach (DataGridViewColumn col in dgvFdConfigs.Columns) { if (col.Name == "FdNum") { col.ReadOnly = true; continue; } // 按钮列不需要设置 ReadOnly 属性 if (col is DataGridViewButtonColumn) continue; // 其他列根据参数设置 col.ReadOnly = readOnly; } } /// /// 初始化分档DataGrid /// //private void SetupFDDataGridView() //{ // // 设置基本属性 // dgvFdConfigs.AutoGenerateColumns = false; // dgvFdConfigs.MultiSelect = false; // // 先清空列,避免重复添加 // dgvFdConfigs.Columns.Clear(); // // 确保 GradeTypes 不为空 // if (GradeTypes == null || GradeTypes.Count == 0) // { // GradeTypes = new List { "不设置", "NG" }; // } // // 创建分档类型的副本作为数据源 // var gradeTypeList = new List(GradeTypes); // // 添加数据列 // dgvFdConfigs.Columns.AddRange(new DataGridViewColumn[] // { //new DataGridViewTextBoxColumn //{ // Name = "FdNum", // HeaderText = "序号", // DataPropertyName = "FdNum", // ReadOnly = true, // Width = 80, // ValueType = typeof(int) //}, //#region 分档类型 - 使用 List 作为数据源 //new DataGridViewComboBoxColumn //{ // Name = "Grade1", // HeaderText = "码垛1电池档位", // DataPropertyName = "Grade1", // DataSource = gradeTypeList, // 使用 List 而不是 BindingList // Width = 160, // ValueType = typeof(string), // FlatStyle = FlatStyle.Flat, // DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, // DropDownWidth = 150, // DefaultCellStyle = new DataGridViewCellStyle // { // BackColor = Color.FromArgb(14, 23, 38), // ForeColor = Color.White, // SelectionBackColor = Color.FromArgb(0, 122, 204), // SelectionForeColor = Color.White, // Font = new Font("微软雅黑", 9F) // } //}, //new DataGridViewComboBoxColumn //{ // Name = "Grade2", // HeaderText = "码垛2电池档位", // DataPropertyName = "Grade2", // DataSource = gradeTypeList, // Width = 160, // ValueType = typeof(string), // FlatStyle = FlatStyle.Flat, // DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, // DropDownWidth = 150, // DefaultCellStyle = new DataGridViewCellStyle // { // BackColor = Color.FromArgb(14, 23, 38), // ForeColor = Color.White, // SelectionBackColor = Color.FromArgb(0, 122, 204), // SelectionForeColor = Color.White, // Font = new Font("微软雅黑", 9F) // } //}, //new DataGridViewComboBoxColumn //{ // Name = "Grade3", // HeaderText = "码垛3电池档位", // DataPropertyName = "Grade3", // DataSource = gradeTypeList, // Width = 160, // ValueType = typeof(string), // FlatStyle = FlatStyle.Flat, // DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, // DropDownWidth = 150, // DefaultCellStyle = new DataGridViewCellStyle // { // BackColor = Color.FromArgb(14, 23, 38), // ForeColor = Color.White, // SelectionBackColor = Color.FromArgb(0, 122, 204), // SelectionForeColor = Color.White, // Font = new Font("微软雅黑", 9F) // } //}, //#endregion //#region 开启分档 //new DataGridViewCheckBoxColumn //{ // Name = "IsFDActive", // HeaderText = "开启分档", // DataPropertyName = "IsFDActive", // Width = 80, // ValueType = typeof(bool), // TrueValue = true, // FalseValue = false, // DefaultCellStyle = new DataGridViewCellStyle // { // Alignment = DataGridViewContentAlignment.MiddleCenter // } //}, //#endregion //new DataGridViewButtonColumn //{ // Name = "Edit", // HeaderText = "操作", // Text = "修改".Translated(), // UseColumnTextForButtonValue = true, // Width = 80, // FlatStyle = FlatStyle.Flat //}, //new DataGridViewButtonColumn //{ // Name = "Add", // HeaderText = "操作", // Text = "新增".Translated(), // UseColumnTextForButtonValue = true, // Width = 80, // FlatStyle = FlatStyle.Flat //}, //new DataGridViewButtonColumn //{ // Name = "Delete", // HeaderText = "操作", // Text = "删除".Translated(), // UseColumnTextForButtonValue = true, // Width = 80, // FlatStyle = FlatStyle.Flat //}, //new DataGridViewButtonColumn //{ // Name = "FDConfig", // HeaderText = "设置", // Text = "分档类型".Translated(), // UseColumnTextForButtonValue = true, // Width = 160, // FlatStyle = FlatStyle.Flat //}, // }); // // 设置列为只读 // SetColumnsFDReadOnly(false); // // 绑定事件 // dgvFdConfigs.CellClick += DgvFdConfigs_CellClick; // dgvFdConfigs.CellValidating += DgvFdConfigs_CellValidating; // dgvFdConfigs.CellValueChanged += DgvFdConfigs_CellValueChanged; // dgvFdConfigs.DataError += DgvFdConfigs_DataError; // dgvFdConfigs.EditingControlShowing += DgvFdConfigs_EditingControlShowing; // 添加编辑事件 // // 设置自动调整行高 // dgvFdConfigs.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; // dgvFdConfigs.RowHeadersVisible = false; // dgvFdConfigs.BackgroundColor = Color.FromArgb(14, 23, 38); // dgvFdConfigs.BorderStyle = BorderStyle.None; //} /// /// 初始化分档DataGrid /// private void SetupFDDataGridView() { // 设置基本属性 dgvFdConfigs.AutoGenerateColumns = false; dgvFdConfigs.MultiSelect = false; // 先清空列,避免重复添加 dgvFdConfigs.Columns.Clear(); // 确保 GradeTypes 不为空 if (GradeTypes == null || GradeTypes.Count == 0) { GradeTypes = new List { "不设置", "NG" }; } // 添加数据列 dgvFdConfigs.Columns.AddRange(new DataGridViewColumn[] { new DataGridViewTextBoxColumn { Name = "FdNum", HeaderText = "序号", DataPropertyName = "FdNum", ReadOnly = true, Width = 80, ValueType = typeof(int) }, #region 分档类型 - 直接使用 GradeTypes 作为数据源 new DataGridViewComboBoxColumn { Name = "Grade1", HeaderText = "码垛1电池档位", DataPropertyName = "Grade1", // 使用 BindingSource 实现动态更新 DataSource = new BindingSource { DataSource = GradeTypes }, Width = 160, ValueType = typeof(string), FlatStyle = FlatStyle.Flat, DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, DropDownWidth = 150, DefaultCellStyle = new DataGridViewCellStyle { BackColor = Color.FromArgb(14, 23, 38), ForeColor = Color.White, SelectionBackColor = Color.FromArgb(0, 122, 204), SelectionForeColor = Color.White, Font = new Font("微软雅黑", 9F) } }, new DataGridViewComboBoxColumn { Name = "Grade2", HeaderText = "码垛2电池档位", DataPropertyName = "Grade2", DataSource = new BindingSource { DataSource = GradeTypes }, Width = 160, ValueType = typeof(string), FlatStyle = FlatStyle.Flat, DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, DropDownWidth = 150, DefaultCellStyle = new DataGridViewCellStyle { BackColor = Color.FromArgb(14, 23, 38), ForeColor = Color.White, SelectionBackColor = Color.FromArgb(0, 122, 204), SelectionForeColor = Color.White, Font = new Font("微软雅黑", 9F) } }, new DataGridViewComboBoxColumn { Name = "Grade3", HeaderText = "码垛3电池档位", DataPropertyName = "Grade3", DataSource = new BindingSource { DataSource = GradeTypes }, Width = 160, ValueType = typeof(string), FlatStyle = FlatStyle.Flat, DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, DropDownWidth = 150, DefaultCellStyle = new DataGridViewCellStyle { BackColor = Color.FromArgb(14, 23, 38), ForeColor = Color.White, SelectionBackColor = Color.FromArgb(0, 122, 204), SelectionForeColor = Color.White, Font = new Font("微软雅黑", 9F) } }, #endregion #region 开启分档 new DataGridViewCheckBoxColumn { Name = "IsFDActive", HeaderText = "开启分档", DataPropertyName = "IsFDActive", Width = 80, ValueType = typeof(bool), TrueValue = true, FalseValue = false, DefaultCellStyle = new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleCenter } }, #endregion new DataGridViewButtonColumn { Name = "Edit", HeaderText = "操作", Text = "修改".Translated(), UseColumnTextForButtonValue = true, Width = 80, FlatStyle = FlatStyle.Flat }, new DataGridViewButtonColumn { Name = "Add", HeaderText = "操作", Text = "新增".Translated(), UseColumnTextForButtonValue = true, Width = 80, FlatStyle = FlatStyle.Flat }, new DataGridViewButtonColumn { Name = "Delete", HeaderText = "操作", Text = "删除".Translated(), UseColumnTextForButtonValue = true, Width = 80, FlatStyle = FlatStyle.Flat }, new DataGridViewButtonColumn { Name = "FDConfig", HeaderText = "设置", Text = "分档类型".Translated(), UseColumnTextForButtonValue = true, Width = 160, FlatStyle = FlatStyle.Flat }, }); // 设置列为只读 SetColumnsFDReadOnly(false); // 绑定事件 dgvFdConfigs.CellClick += DgvFdConfigs_CellClick; dgvFdConfigs.CellValidating += DgvFdConfigs_CellValidating; dgvFdConfigs.CellValueChanged += DgvFdConfigs_CellValueChanged; dgvFdConfigs.DataError += DgvFdConfigs_DataError; dgvFdConfigs.EditingControlShowing += DgvFdConfigs_EditingControlShowing; // 设置自动调整行高 dgvFdConfigs.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; dgvFdConfigs.RowHeadersVisible = false; dgvFdConfigs.BackgroundColor = Color.FromArgb(14, 23, 38); dgvFdConfigs.BorderStyle = BorderStyle.None; } /// /// 加载PLCConfig配置文件 /// private void LoadPLCConfig() { try { if (File.Exists(PlcConfigFilePath)) { using (var stream = File.OpenRead(PlcConfigFilePath)) { var devices = MiniExcel.Query(stream).ToList(); plcConfigs = devices.Select(device => new PLCConfig { PlcNum = device.PlcNum, PLCType = device.PLCType, IPAddress = device.IPAddress, Port = device.Port.ToString(), HeartBeat = device.HeartBeat, IsHeartBeat = device.IsHeartBeat, IsActive = device.IsActive, Remark = device.Remark, }).ToList(); } } else { plcConfigs = new List(); } RefreshDataGridView(); // RefreshFDDataGridView(); } catch (Exception ex) { MessageBox.Show($"加载配置文件失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); plcConfigs = new List(); } } private void LoadFDConfig() { try { fdConfigs = CommonMethods.fdConfigs ?? new List(); // 确保所有分档值都在 GradeTypes 列表中 if (GradeTypes != null && GradeTypes.Any()) { ValidateAllGradeValues(); } RefreshFDDataGridView(); } catch (Exception ex) { MessageBox.Show($"加载配置文件失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); fdConfigs = new List(); } } /// /// 刷新分档类型的下拉列表 /// public void RefreshGradeTypes() { try { // 重新加载分档类型 CommonMethods.LoadFDGradeTypes(); GradeTypes = new List(CommonMethods.FDGradeTypes); // 确保 "不设置" 和 "NG" 在列表中 if (!GradeTypes.Contains("不设置")) GradeTypes.Insert(0, "不设置"); if (!GradeTypes.Contains("NG")) GradeTypes.Add("NG"); // 更新 ComboBox 列的数据源 foreach (DataGridViewColumn col in dgvFdConfigs.Columns) { if (col is DataGridViewComboBoxColumn comboCol && (col.Name == "Grade1" || col.Name == "Grade2" || col.Name == "Grade3")) { // 先保存当前数据 var currentData = new List(); if (dgvFdConfigs.DataSource is BindingList bindingList) { currentData = bindingList.ToList(); } // 更新数据源 comboCol.DataSource = null; comboCol.DataSource = new List(GradeTypes); // 恢复数据 if (currentData.Any()) { fdConfigs = currentData; RefreshFDDataGridView(); } } } // 验证并修复所有分档值 ValidateAllGradeValues(); dgvFdConfigs.Refresh(); } catch (Exception ex) { MessageBox.Show($"刷新分档类型失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /// /// 验证所有分档值是否在列表中 /// private void ValidateAllGradeValues() { if (fdConfigs == null || !fdConfigs.Any()) return; bool needRefresh = false; foreach (var config in fdConfigs) { if (!string.IsNullOrEmpty(config.Grade1) && !GradeTypes.Contains(config.Grade1)) { config.Grade1 = "不设置"; needRefresh = true; } if (!string.IsNullOrEmpty(config.Grade2) && !GradeTypes.Contains(config.Grade2)) { config.Grade2 = "不设置"; needRefresh = true; } if (!string.IsNullOrEmpty(config.Grade3) && !GradeTypes.Contains(config.Grade3)) { config.Grade3 = "不设置"; needRefresh = true; } } if (needRefresh) { RefreshFDDataGridView(); } } /// /// 从全局加载分档类型 /// private void LoadFDGradeTypesFromGlobal() { // 确保全局分档类型已加载 if (CommonMethods.FDGradeTypes == null || CommonMethods.FDGradeTypes.Count == 0) { CommonMethods.LoadFDGradeTypes(); } GradeTypes = new List(CommonMethods.FDGradeTypes); } private void DgvPlcConfigs_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; var columnName = dgvPlcConfigs.Columns[e.ColumnIndex].Name; // 如果正在编辑其他行,阻止操作 if (isEditing && editingRowIndex != e.RowIndex) { MessageBox.Show("请先完成当前编辑操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var plcConfig = plcConfigs[e.RowIndex]; switch (columnName) { case "Edit": HandleEdit(e.RowIndex); break; case "CommConfig": HandleCommConfig(plcConfig); break; case "VariableConfig": HandleVariableConfig(plcConfig); break; case "Delete": HandleDelete(e.RowIndex, plcConfig); break; } } private void DgvFdConfigs_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; var columnName = dgvFdConfigs.Columns[e.ColumnIndex].Name; // 如果正在编辑其他行,阻止操作 if (isFDEditing && editingFDRowIndex != e.RowIndex) { MessageBox.Show("请先完成当前编辑操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var fdConfig = fdConfigs[e.RowIndex]; switch (columnName) { case "Edit": HandleFDEdit(e.RowIndex); break; case "Add": HandleFDAdd(e.RowIndex, fdConfig); break; case "Delete": HandleFDDelete(e.RowIndex, fdConfig); break; case "FDConfig": HandleFDConfig(fdConfig); break; } } private void DgvFdConfigs_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { // 确保是 ComboBox 编辑控件 if (e.Control is ComboBox comboBox) { // 移除可能存在的旧事件处理器,防止重复订阅 comboBox.SelectedIndexChanged -= ComboBox_SelectedIndexChanged; comboBox.TextChanged -= ComboBox_TextChanged; // 根据列名添加事件 string columnName = dgvFdConfigs.CurrentCell?.OwningColumn?.Name; if (columnName == "Grade1" || columnName == "Grade2" || columnName == "Grade3") { comboBox.DropDownStyle = ComboBoxStyle.DropDownList; comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; } } } private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) { // 提交编辑,确保数据更新 dgvFdConfigs.CommitEdit(DataGridViewDataErrorContexts.Commit); } private void ComboBox_TextChanged(object sender, EventArgs e) { // 处理文本变化 if (sender is ComboBox comboBox) { string text = comboBox.Text; if (!string.IsNullOrEmpty(text) && !GradeTypes.Contains(text)) { // 如果输入的值不在列表中,自动选择第一个 if (GradeTypes.Count > 0) { comboBox.SelectedIndex = 0; } } } } private void HandleFDConfig(FDConfig config) { using (var fdForm = new FDConfigForm()) { if (fdForm.ShowDialog() == DialogResult.OK) { // 如果需要刷新主窗体数据 RefreshFDDataGridView(); } } } // 相应地,在处理编辑状态时,也需要修改 HandleEdit 方法 private void HandleEdit(int rowIndex) { if (!isEditing) { // 开始编辑 isEditing = true; editingRowIndex = rowIndex; SetColumnsReadOnly(false); // 设置其他列为可编辑 // 更改编辑按钮文本为"保存" dgvPlcConfigs.Rows[rowIndex].Cells["Edit"].Value = "保存"; // 禁用其他行的按钮 foreach (DataGridViewRow row in dgvPlcConfigs.Rows) { if (row.Index != rowIndex) { if (row.Cells["Edit"] is DataGridViewButtonCell editCell) editCell.Value = ""; if (row.Cells["CommConfig"] is DataGridViewButtonCell configCell) configCell.Value = ""; if (row.Cells["Delete"] is DataGridViewButtonCell deleteCell) deleteCell.Value = ""; } } // 禁用添加按钮 btAddPLC.Enabled = false; } else if (rowIndex == editingRowIndex) { // 保存更改 if (ValidateRow(rowIndex)) { SaveChanges(rowIndex); EndEditing(); } } } private void HandleFDEdit(int rowIndex) { if (!isFDEditing) { // 开始编辑 isFDEditing = true; editingFDRowIndex = rowIndex; SetColumnsFDReadOnly(false); // 设置其他列为可编辑 // 更改编辑按钮文本为"保存" dgvFdConfigs.Rows[rowIndex].Cells["Edit"].Value = "保存"; // 禁用其他行的按钮 foreach (DataGridViewRow row in dgvFdConfigs.Rows) { if (row.Index != rowIndex) { if (row.Cells["Edit"] is DataGridViewButtonCell editCell) editCell.Value = ""; } } // 禁用添加按钮 //btAddPLC.Enabled = false; RefreshFDDataGridView(); } else if (rowIndex == editingFDRowIndex) { if (!ValidateFDRow(rowIndex)) return; SaveFDChanges(rowIndex); EndFDEditing(); } } private void EndEditing() { isEditing = false; editingRowIndex = -1; SetColumnsReadOnly(true); // 恢复所有按钮文本和状态 foreach (DataGridViewRow row in dgvPlcConfigs.Rows) { row.Cells["Edit"].Value = "编辑"; row.Cells["CommConfig"].Value = "通信组"; row.Cells["Delete"].Value = "删除"; } // 启用添加按钮 btAddPLC.Enabled = true; } private void EndFDEditing() { isFDEditing = false; editingFDRowIndex = -1; SetColumnsFDReadOnly(true); // 恢复所有按钮文本和状态 foreach (DataGridViewRow row in dgvFdConfigs.Rows) { row.Cells["Edit"].Value = "编辑"; } // 启用添加按钮 btAddPLC.Enabled = true; } private void HandleCommConfig(PLCConfig config) { using (var commForm = new CommunicationEditForm(config.PlcNum)) { if (commForm.ShowDialog() == DialogResult.OK) { // 如果需要刷新主窗体数据 RefreshDataGridView(); } } } private void HandleVariableConfig(PLCConfig config) { using (var commForm = new VariableEditForm(config.PlcNum)) { if (commForm.ShowDialog() == DialogResult.OK) { // 如果需要刷新主窗体数据 RefreshDataGridView(); } } } private void HandleDelete(int rowIndex, PLCConfig config) { if (MessageBox.Show($"确定要删除 PLC {config.PlcNum} 吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { plcConfigs.RemoveAt(rowIndex); SavePLCConfig(); RefreshDataGridView(); } } private void HandleFDAdd(int rowIndex, FDConfig fdconfig) { if (isFDEditing) { MessageBox.Show("请先完成当前分档编辑操作".Translated(), "提示".Translated(), MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // 自动生成最大FdNum int maxFdNum = fdConfigs.Any() ? fdConfigs.Max(x => x.FdNum) : 0; var newFd = new FDConfig { FdNum = maxFdNum + 1, Grade1 = "不设置", Grade2 = "不设置", Grade3 = "不设置", IsFDActive = false, //IsNGActive = false }; fdConfigs.Add(newFd); RefreshFDDataGridView(); // 自动进入编辑状态 int newRow = dgvFdConfigs.Rows.Count - 1; HandleFDEdit(newRow); } private void HandleFDDelete(int rowIndex, FDConfig fdconfig) { if (MessageBox.Show($"确定要删除 分档 {fdconfig.FdNum} 吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { fdConfigs.RemoveAt(rowIndex); SaveFDConfig(); RefreshFDDataGridView(); } } private bool ValidateRow(int rowIndex) { var row = dgvPlcConfigs.Rows[rowIndex]; // IP地址验证 string ipAddress = row.Cells["IPAddress"].Value?.ToString(); if (!IsValidIPAddress(ipAddress)) { MessageBox.Show("请输入有效的IP地址", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } // 端口验证 string port = row.Cells["Port"].Value?.ToString(); if (!IsValidPort(port)) { MessageBox.Show("端口号必须在0-65535之间", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } // PLC类型验证 string plcType = row.Cells["PLCType"].Value?.ToString(); if (string.IsNullOrWhiteSpace(plcType)) { MessageBox.Show("请选择PLC类型", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } return true; } private void SaveChanges(int rowIndex) { try { var row = dgvPlcConfigs.Rows[rowIndex]; var config = plcConfigs[rowIndex]; // 更新配置对象 config.PLCType = row.Cells["PLCType"].Value?.ToString() ?? ""; config.IPAddress = row.Cells["IPAddress"].Value?.ToString() ?? ""; config.Port = row.Cells["Port"].Value?.ToString() ?? ""; config.HeartBeat = row.Cells["HeartBeat"].Value?.ToString() ?? ""; config.IsHeartBeat = row.Cells["IsHeartBeat"].Value != null && Convert.ToBoolean(row.Cells["IsHeartBeat"].Value); config.IsActive = row.Cells["IsActive"].Value != null && Convert.ToBoolean(row.Cells["IsActive"].Value); config.Remark = row.Cells["Remark"].Value?.ToString() ?? ""; //foreach (var plc in CommonMethods.plcDevices) //{ // foreach (var deviceConfig in plcDevices) // { // } //} // 保存更改 SavePLCConfig(); MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { // 这里只显示错误信息,不再抛出异常 MessageBox.Show($"保存失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void SaveFDChanges(int rowIndex) { try { var row = dgvFdConfigs.Rows[rowIndex]; var config = fdConfigs[rowIndex]; config.Grade1 = row.Cells["Grade1"].Value?.ToString() ?? ""; config.Grade2 = row.Cells["Grade2"].Value?.ToString() ?? ""; config.Grade3 = row.Cells["Grade3"].Value?.ToString() ?? ""; config.IsFDActive = row.Cells["IsFDActive"].Value != null && Convert.ToBoolean(row.Cells["IsFDActive"].Value); //config.IsNGActive = row.Cells["IsNGActive"].Value != null && // Convert.ToBoolean(row.Cells["IsNGActive"].Value); CommonMethods.curFdConfig = config; // 保存更改 SaveFDConfig(); SendFDConfigToPLC(); MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { // 这里只显示错误信息,不再抛出异常 MessageBox.Show($"保存失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void DgvPlcConfigs_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.RowIndex < 0 || !isEditing || e.RowIndex != editingRowIndex) return; string newValue = e.FormattedValue.ToString(); var column = dgvPlcConfigs.Columns[e.ColumnIndex]; switch (column.Name) { case "IPAddress": if (!IsValidIPAddress(newValue)) { e.Cancel = true; dgvPlcConfigs.Rows[e.RowIndex].ErrorText = "请输入有效的IP地址"; } break; case "Port": if (!IsValidPort(newValue)) { e.Cancel = true; dgvPlcConfigs.Rows[e.RowIndex].ErrorText = "请输入有效的端口号(0-65535)"; } break; } } private void DgvFdConfigs_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.RowIndex < 0 || !isFDEditing || e.RowIndex != editingFDRowIndex) return; string newValue = e.FormattedValue.ToString(); var column = dgvFdConfigs.Columns[e.ColumnIndex]; } private void DgvPlcConfigs_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; dgvPlcConfigs.Rows[e.RowIndex].ErrorText = string.Empty; } private void DgvFdConfigs_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; dgvFdConfigs.Rows[e.RowIndex].ErrorText = string.Empty; } private void DgvPlcConfigs_DataError(object sender, DataGridViewDataErrorEventArgs e) { e.ThrowException = false; string columnName = dgvPlcConfigs.Columns[e.ColumnIndex].HeaderText; MessageBox.Show($"'{columnName}'列的输入数据格式不正确", "数据错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void DgvFdConfigs_DataError(object sender, DataGridViewDataErrorEventArgs e) { e.ThrowException = false; string columnName = dgvFdConfigs.Columns[e.ColumnIndex]?.Name ?? ""; // 如果是分档列的数据错误,尝试修复 if (columnName == "Grade1" || columnName == "Grade2" || columnName == "Grade3") { try { // 获取当前单元格 var cell = dgvFdConfigs.Rows[e.RowIndex].Cells[e.ColumnIndex]; // 如果当前值不在列表中,设置为 "不设置" string currentValue = cell.Value?.ToString(); if (!string.IsNullOrEmpty(currentValue) && !GradeTypes.Contains(currentValue)) { cell.Value = "不设置"; // 刷新显示 dgvFdConfigs.Refresh(); return; } } catch { // 如果修复失败,忽略错误 } } } /// /// 验证IP地址 /// /// /// private bool IsValidIPAddress(string ip) { if (string.IsNullOrWhiteSpace(ip)) return false; try { // 分割IP地址 string[] parts = ip.Split('.'); if (parts.Length != 4) return false; // 验证每个部分 foreach (string part in parts) { if (!int.TryParse(part, out int number)) return false; if (number < 0 || number > 255) return false; } return true; } catch { return false; } } private bool IsValidPort(string port) { if (string.IsNullOrWhiteSpace(port)) return false; return int.TryParse(port, out int portNum) && portNum >= 0 && portNum <= 65535; } private void SavePLCConfig() { try { SafeSaveExcel(PlcConfigFilePath, plcConfigs); } catch (Exception ex) { MessageBox.Show($"PLC配置保存失败:{ex.Message}".Translated(), "错误".Translated(), MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } } private void SaveFDConfig() { try { SafeSaveExcel(FdConfigFilePath, fdConfigs); CommonMethods.fdConfigs = fdConfigs; } catch (Exception ex) { MessageBox.Show($"分档配置保存失败:{ex.Message}".Translated(), "错误".Translated(), MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } } /// /// 安全保存Excel,临时文件原子替换,防止文件损坏 /// private void SafeSaveExcel(string filePath, List data) { string dir = Path.GetDirectoryName(filePath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); // 备份原文件 if (File.Exists(filePath)) { string bak = $"{filePath}.bak"; File.Copy(filePath, bak, true); } string tempPath = Path.Combine(dir, $"_tmp_{Path.GetFileName(filePath)}"); try { MiniExcel.SaveAs(tempPath, data, overwriteFile: true); if (File.Exists(filePath)) File.Delete(filePath); File.Move(tempPath, filePath); } catch (Exception ex) { if (File.Exists(tempPath)) File.Delete(tempPath); throw new Exception($"保存配置失败:{ex.Message}", ex); } } private void RefreshDataGridView() { dgvPlcConfigs.DataSource = null; dgvPlcConfigs.DataSource = new BindingList(plcConfigs); } private void RefreshFDDataGridView() { dgvFdConfigs.DataSource = null; dgvFdConfigs.DataSource = new BindingList(fdConfigs); } private void FDConfigForm_OnFDConfigChanged(object sender, EventArgs e) { // 刷新分档类型下拉列表 RefreshGradeTypes(); } protected override void OnFormClosing(FormClosingEventArgs e) { FDConfigForm.OnFDConfigChanged -= FDConfigForm_OnFDConfigChanged; base.OnFormClosing(e); bool needCancel = false; // PLC编辑未保存 if (isEditing) { var res = MessageBox.Show("当前PLC配置存在未保存修改,是否保存?".Translated(), "保存确认".Translated(), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (res == DialogResult.Yes) { if (!ValidateRow(editingRowIndex)) needCancel = true; else { SaveChanges(editingRowIndex); EndEditing(); } } else if (res == DialogResult.Cancel) needCancel = true; } // FD分档编辑未保存 if (isFDEditing && !needCancel) { var res = MessageBox.Show("当前分档配置存在未保存修改,是否保存?".Translated(), "保存确认".Translated(), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (res == DialogResult.Yes) { SaveFDChanges(editingFDRowIndex); EndFDEditing(); } else if (res == DialogResult.Cancel) needCancel = true; } e.Cancel = needCancel; } private bool ValidateFDRow(int rowIndex) { var row = dgvFdConfigs.Rows[rowIndex]; string g1 = row.Cells["Grade1"].Value?.ToString(); string g2 = row.Cells["Grade2"].Value?.ToString(); string g3 = row.Cells["Grade3"].Value?.ToString(); if (string.IsNullOrWhiteSpace(g1) || string.IsNullOrWhiteSpace(g2) || string.IsNullOrWhiteSpace(g3)) { MessageBox.Show("机架档位不能为空".Translated(), "验证错误".Translated(), MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } return true; } /// /// 添加PLC /// /// /// private void btAddPLC_Click(object sender, EventArgs e) { if (isEditing) { MessageBox.Show("请先完成当前编辑操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var maxPlcNum = plcConfigs.Count > 0 ? plcConfigs.Max(p => p.PlcNum) : 0; var newConfig = new PLCConfig { PlcNum = maxPlcNum + 1, PLCType = "", IPAddress = "", Port = "", HeartBeat = "", IsHeartBeat = false, IsActive = false, Remark = "" }; plcConfigs.Add(newConfig); RefreshDataGridView(); // 自动开始编辑新行 int newRowIndex = dgvPlcConfigs.Rows.Count - 1; HandleEdit(newRowIndex); } private void BtnSaveAll_Click(object sender, EventArgs e) { try { SavePLCConfig(); MessageBox.Show("所有配置已保存", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show($"保存失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } #region 系统相关配置 private void tog_AutoLogin_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveAutoLogin(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改软件自动登录方式".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void tog_AutoStart_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveAutoStart(((Toggle)sender).IsChecked)) { //写入注册表 AutoStart(((Toggle)sender).IsChecked); CommonMethods.AddOPLog(false, "修改软件自动启动方式".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void tog_AutoLock_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveAutoLock(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改无操作自动锁屏方式".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void up_LockPeriod_ValueChanged(object sender, EventArgs e) { if (CommonMethods.SaveLockPeriod(Convert.ToInt32(((UpDownLabel)sender).CurrentValue))) { CommonMethods.AddOPLog(false, "修改锁屏间隔时间".Translated() + ":" + ((UpDownLabel)sender).CurrentValue.ToString()); CommonMethods.GetSysConfig(); } } private void tog_AutoQieHuanM_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveAutoQieHuanM(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改无操作自动切换监控界面方式".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void tog_IsDebugMod_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveIsDebug(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改调试模式".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void tog_Wuliu_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveWuLiu(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改处理物流线分拣".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void up_QieHuanPeriod_ValueChanged(object sender, EventArgs e) { if (CommonMethods.SaveQieHuanMPeriod(Convert.ToInt32(((UpDownLabel)sender).CurrentValue))) { CommonMethods.AddOPLog(false, "修改切换监控界面间隔时间".Translated() + ":" + ((UpDownLabel)sender).CurrentValue.ToString()); CommonMethods.GetSysConfig(); } } private void up_ShowSeriesCount_ValueChanged(object sender, EventArgs e) { if (CommonMethods.SaveShowSeriesCount(Convert.ToInt32(((UpDownLabel)sender).CurrentValue))) { CommonMethods.AddOPLog(false, "修改曲线显示数量".Translated() + ":" + ((UpDownLabel)sender).CurrentValue.ToString()); CommonMethods.GetSysConfig(); } } private void tog_SwipeCardMode_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveSwipeCardMode(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改刷卡模式".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); if (CommonMethods.sysConfig.SwipeCardMode && CommonMethods.IsLoginOk) { DialogResult dialogResult1 = new FrmMsgBoxWithAck("当前已登录".Translated() + "," + "是否切换刷卡模式".Translated(), "提示".Translated()).ShowDialog(); if (dialogResult1 == DialogResult.OK) { CommonMethods.AddOPLog(false, $"切换刷卡模式成功".Translated() + "," + "当前用户已注销".Translated()); CommonMethods.IsLoginOk = false; CommonMethods.sysConfig.SwipeCardMode = true; this.tog_SwipeCardMode.IsChecked = CommonMethods.sysConfig.SwipeCardMode; CommonMethods.SaveSwipeCardMode(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); //切屏 CommonMethods.sysConfig.ScreenCutting = true; } else { CommonMethods.IsLoginOk = true; CommonMethods.sysConfig.SwipeCardMode = false; this.tog_SwipeCardMode.IsChecked = CommonMethods.sysConfig.SwipeCardMode; CommonMethods.SaveSwipeCardMode(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); } } } } private void tog_OpenMesModel_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.plcDevices.Count() > 0) { for (int i = 0; i < CommonMethods.plcDevices.Count(); i++) { if (CommonMethods.plcDevices[i].IsConnected && CommonMethods.plcDevices[i].Name == "PLC_1") { this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching; CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); new FrmMsgBoxOutWithAck(2, "先停止运行再切换MES".Translated(), "提示".Translated()).ShowDialog(); return; } } } if (CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改MES/非MES模式切换".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); if (CommonMethods.sysConfig.MesModeSwitching) { FrmLoginMes frmLoginMes = new FrmLoginMes(); if (frmLoginMes.ShowDialog() != DialogResult.OK) { CommonMethods.sysConfig.MesModeSwitching = false; this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching; CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); } } else { DialogResult dialogResult = new FrmMsgBoxWithAck("是否关闭MES模式".Translated(), "提示".Translated()).ShowDialog(); if (dialogResult == DialogResult.OK) { CommonMethods.AddOPLog(false, "关闭MES模式成功".Translated() + "," + "MES用户已注销".Translated()); CommonMethods.sysConfig.MesModeSwitching = false; this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching; CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); } else { CommonMethods.sysConfig.MesModeSwitching = true; this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching; CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); } } } } private void tog_finishSwitch_CheckedChanged(object sender, EventArgs e) { var toggle = (Toggle)sender; bool targetVal = toggle.IsChecked; // 检测PLC在线禁止切换 if (CommonMethods.plcDevices.Any(p => p.IsConnected)) { new FrmMsgBoxOutWithAck(2, "先停止运行再切换成品/半成品模式".Translated(), "提示".Translated()).ShowDialog(); // 恢复原始值 toggle.IsChecked = CommonMethods.sysConfig.FinishSwitching; return; } var res = MessageBox.Show($"确定切换为{(targetVal ? "成品模式" : "半成品模式")}".Translated(), "确认切换".Translated(), MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (res != DialogResult.Yes) { toggle.IsChecked = CommonMethods.sysConfig.FinishSwitching; return; } // 保存配置 CommonMethods.SaveFinishSwitch(targetVal); CommonMethods.sysConfig.FinishSwitching = targetVal; CommonMethods.AddOPLog(false, $"切换成品模式:{targetVal}".Translated()); CommonMethods.GetSysConfig(); } private void tog_GetMesParam_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveGetMesParam(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改获取MES参数".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void tog_SaveThreadTime_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveSaveThreadTime(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改线程耗时日志保存".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } /// /// 修改程序在注册表的 键值 /// /// private void AutoStart(bool isAuto = true) { if (isAuto == true) { RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run"); R_run.SetValue("KYJPro", System.Windows.Forms.Application.ExecutablePath); R_run.Close(); R_local.Close(); } else { RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run"); R_run.DeleteSubKey("KYJPro", false); R_run.Close(); R_local.Close(); } } #endregion private void btn_Sure_Click(object sender, EventArgs e) { CommonMethods.Configxml["MES_CONFIG"]["SiteCode"] = this.txtFactory_code.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["LineCode"] = this.txtline_No.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["EquipNum"] = this.txtEqp_code.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["CustomerPartNum"] = this.txtCustomerPartNum.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["EmployeeAuthCheck"] = this.txtEmployeeAuthCheck.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["DeviceParamRequest"] = this.txtDeviceParamRequest.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["DeviceParamChange"] = this.txtDeviceParamChange.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["QueryTrayUrl"] = this.txtQueryTray.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["QueryGradeUrl"] = this.txtQueryGrade.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["UpResultParamUrl"] = this.txtUpResultParam.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["unBindTrayUrl"] = this.txtUnbind.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["PackLoadUrl"] = this.txtPack.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["FinishedPackLoadUrl"] = this.txtBox_finishedBattery.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["DeviceAlarm"] = this.txtDeviceAlarm.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["DeviceStatus"] = this.txtDeviceStatus.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["EnergyConsumption"] = this.txtEnergyConsumption.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["Anemometer"] = this.txtAnemometer.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["APPID"] = this.txtAppID.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["APPKEY"] = this.txtAppKey.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["GetTokenUrl"] = this.txtGetToken.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["MaterialCode"] = this.txtBox_materialCode.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["PackLayers"] = this.upDown_layer.CurrentValue.ToString(); CommonMethods.Configxml["MES_CONFIG"]["RowsPerLayer"] = this.upDown_row.CurrentValue.ToString(); CommonMethods.Configxml["MES_CONFIG"]["ColsPerLayer"] = this.upDown_Col.CurrentValue.ToString(); CommonMethods.WriteXmlFile(CommonMethods.Configxml, CommonMethods.xmlFilePath); CommonMethods.mesConfig = CommonMethods.GetMesConfig(); DialogResult dialogResult = new FrmMsgBoxOutWithAck(1, "参数修改成功", "参数设置").ShowDialog(); } /// /// 取消 /// /// /// private void btn_Cancel_Click(object sender, EventArgs e) { this.txtFactory_code.Text = CommonMethods.mesConfig.siteCode; this.txtline_No.Text = CommonMethods.mesConfig.lineCode; this.txtEqp_code.Text = CommonMethods.mesConfig.equipNum; this.txtCustomerPartNum.Text = CommonMethods.mesConfig.CustomerPartNum; this.txtAppID.Text = CommonMethods.mesConfig.AppID; this.txtAppKey.Text = CommonMethods.mesConfig.AppKey; this.txtGetToken.Text = CommonMethods.mesConfig.GetTokenUrl; } #region 减少闪烁 protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= 0x02000000; return cp; } } #endregion private void btnFdConfig_Click(object sender, EventArgs e) { this.dgvFdConfigs.Visible = true; this.dgvPlcConfigs.Visible = false; } private void btnPlcConfig_Click(object sender, EventArgs e) { this.dgvFdConfigs.Visible = false; this.dgvPlcConfigs.Visible = true; } private void txt_equipNo_TextChanged(object sender, EventArgs e) { string newEquipNo = this.txt_equipNo.Text.Trim(); if (CommonMethods.SaveEquipNo(newEquipNo)) { CommonMethods.AddOPLog(true, "修改机架号".Translated() + ":" + newEquipNo); CommonMethods.GetSysConfig(); } } /// /// 下发分档配置到PLC /// private void SendFDConfigToPLC() { try { // 下发到PLC foreach (var plcDevice in CommonMethods.plcDevices) { if (plcDevice == null || !plcDevice.IsConnected) continue; // 调用ControlCenter下发配置 Task.Run(async () => await ControlCenter.Instance.SendConfigToPLCAsync(plcDevice)); } MessageBox.Show("分档配置已下发到PLC", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show($"下发分档配置失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }