using JinYuan.ControlLib; using JinYuan.MES.Models; using JinYuan.Models; using JinYuan.VirtualDataLibrary; using Language; using Microsoft.Win32; using MiniExcelLibs; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Eventing.Reader; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using System.Drawing.Printing; namespace LargeSquareOne { public partial class FrmSystemSet : MultiLanguageForm { private string devPath = string.Empty; private string PlcConfigFilePath = "plc_config.xlsx"; private List plcConfigs; private string PlcCommunicationConfigPath; private string variableConfigPath; private List PLCTypes = new List(); private bool isEditing = false; private int editingRowIndex = -1; private readonly string configFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config"); public FrmSystemSet(string devPath) { InitializeComponent(); ////设置控件样式,去除缓冲 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 = Path.Combine(configFolderPath, "Device.xlsx"); PlcCommunicationConfigPath = Path.Combine(configFolderPath, "Group.xlsx"); variableConfigPath = Path.Combine(configFolderPath, "Variable.xlsx"); devPath = Path.Combine(configFolderPath, "Configure.ini"); PLCTypes.AddRange(new string[] { "OmronFinsTCP", "OmronCipNet" }); SetupDataGridView(); LoadPLCConfig(); 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_GetMesParam.IsChecked = CommonMethods.sysConfig.GetMesParam; this.tog_SaveThreadTime.IsChecked = CommonMethods.sysConfig.SaveThreadTime; 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_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.devPath = devPath; 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; string customerType = CommonMethods.mesConfig.customerType; switch (customerType) { case "O2": this.radio_O2.Checked = true; break; default: this.radio_other.Checked = true; break; } this.txtEmployeeAuthCheck.Text = CommonMethods.mesConfig.EmployeeAuthCheck; this.txtCartonInfo.Text = CommonMethods.mesConfig.queryCartonUrl; this.txtPalletInfo.Text = CommonMethods.mesConfig.queryPalletUrl; this.txtDeviceParamRequest.Text = CommonMethods.mesConfig.DeviceParamRequest; this.txtDeviceParamChange.Text = CommonMethods.mesConfig.DeviceParamChange; 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.txtBindingLabel.Text = CommonMethods.mesConfig.bindingUrl; this.tog_ConnectPrinter.IsChecked = CommonMethods.btwConfig.IsConnectPrinter; this.tog_ConnectPrinter.CheckedChanged += new System.EventHandler(this.tog_ConnectPrinter_CheckedChanged); this.txtBox_containerPath.Text = CommonMethods.btwConfig.containerBTWPath; this.txtBox_palletpath.Text = CommonMethods.btwConfig.palletBTWPath; LoadPrintersToComboBox(CommonMethods.btwConfig.printerName); } /// /// 加载打印机列表到ComboBox /// private void LoadPrintersToComboBox(string lastprinterName) { try { // 清空原有项 this.combox_printer.Items.Clear(); string systemDefaultPrinter = new PrinterSettings().PrinterName; string targetDefaultPrinter = string.IsNullOrEmpty(lastprinterName) ? systemDefaultPrinter : lastprinterName; // 遍历所有打印机并添加到ComboBox foreach (string printerName in PrinterSettings.InstalledPrinters) { string displayText = printerName == targetDefaultPrinter ? $"{printerName} (默认)" : printerName; this.combox_printer.Items.Add(displayText); } string finalSelectedPrinter = string.Empty; if (this.combox_printer.Items.Count > 0) { bool isSelected = false; string targetDisplayText = $"{targetDefaultPrinter} (默认)"; for (int i = 0; i < combox_printer.Items.Count; i++) { if (combox_printer.Items[i].ToString() == targetDisplayText) { combox_printer.SelectedIndex = i; isSelected = true; finalSelectedPrinter = targetDefaultPrinter; break; } } if (!isSelected) { for (int i = 0; i < combox_printer.Items.Count; i++) { if (combox_printer.Items[i].ToString() == targetDefaultPrinter) { combox_printer.SelectedIndex = i; isSelected = true; finalSelectedPrinter = targetDefaultPrinter; break; } } } // 仍未选中则选第一个 if (!isSelected) { combox_printer.SelectedIndex = 0; finalSelectedPrinter = combox_printer.Items[0].ToString().Replace(" (默认)", "").Trim(); ; } CommonMethods.btwConfig.printerName = finalSelectedPrinter; } else { combox_printer.Items.Add("未检测到打印机"); combox_printer.SelectedIndex = 0; CommonMethods.btwConfig.printerName = string.Empty; MessageBox.Show($"未检测到打印机, 请确认打印机的连接是否正常", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show($"加载打印机列表失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// /// 初始化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; } } /// /// 加载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(); } catch (Exception ex) { MessageBox.Show($"加载配置文件失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); plcConfigs = new List(); } } 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 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 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 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 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() ?? ""; // 保存更改 SavePLCConfig(); 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 DgvPlcConfigs_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; dgvPlcConfigs.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); } /// /// 验证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 { // 创建备份 if (File.Exists(PlcConfigFilePath)) { string backupFile = $"{PlcConfigFilePath}.bak"; File.Copy(PlcConfigFilePath, backupFile, true); } // 直接保存到目标文件 MiniExcel.SaveAs(PlcConfigFilePath, plcConfigs, overwriteFile: true); } catch (IOException ex) { MessageBox.Show($"保存文件时发生IO错误:{ex.Message}\n请确保文件未被其他程序占用。", "保存错误", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } catch (UnauthorizedAccessException ex) { MessageBox.Show($"没有足够的权限保存文件:{ex.Message}\n请确保有写入权限。", "权限错误", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } catch (Exception ex) { MessageBox.Show($"保存配置时发生错误:{ex.Message}", "保存错误", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } } private void RefreshDataGridView() { dgvPlcConfigs.DataSource = null; dgvPlcConfigs.DataSource = new BindingList(plcConfigs); } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); if (isEditing) { var result = MessageBox.Show("当前有未保存的更改,是否保存?", "保存确认", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); switch (result) { case DialogResult.Yes: if (ValidateRow(editingRowIndex)) { SaveChanges(editingRowIndex); EndEditing(); } else { e.Cancel = true; } break; case DialogResult.Cancel: e.Cancel = true; break; } } } /// /// 添加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 tog_ConnectPrinter_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveConnectPrinter(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改是否连接打印机服务器标记".Translated() + ":" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetBtwConfig(); } } 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 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[0].IsConnected && CommonMethods.sysConfig.MesModeSwitching) { CommonMethods.sysConfig.MesModeSwitching = true; this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching; CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); new FrmMsgBoxOutWithAck(2, "先停止运行再切换MES".Translated(), "提示".Translated()).ShowDialog(); return; } if (CommonMethods.plcDevices[0].IsConnected && !CommonMethods.sysConfig.MesModeSwitching) { CommonMethods.sysConfig.MesModeSwitching = false; 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_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"]["EmployeeAuthCheck"] = this.txtEmployeeAuthCheck.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["QueryCartonUrl"] = this.txtCartonInfo.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["DeviceParamRequest"] = this.txtDeviceParamRequest.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["DeviceParamChange"] = this.txtDeviceParamChange.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["QueryPalletUrl"] = this.txtPalletInfo.Text.Trim(); CommonMethods.Configxml["MES_CONFIG"]["BindingUrl"] = this.txtBindingLabel.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"]["MaterialCode"] = this.txtBox_materialCode.Text.Trim(); string customerType = this.radio_O2.Checked ? "O2" : "other"; CommonMethods.Configxml["MES_CONFIG"]["CustomerType"] = customerType; CommonMethods.Configxml["BTW_CONFIG"]["IsConnectPrinter"] = this.tog_ConnectPrinter.Text.Trim(); CommonMethods.Configxml["BTW_CONFIG"]["ContainerBTWPath"] = this.txtBox_containerPath.Text.Trim(); CommonMethods.Configxml["BTW_CONFIG"]["PalletBTWPath"] = this.txtBox_palletpath.Text.Trim(); if (combox_printer.SelectedItem != null && combox_printer.SelectedItem.ToString() != "未检测到打印机") { string selectedPrinter = combox_printer.SelectedItem.ToString(); CommonMethods.Configxml["BTW_CONFIG"]["PrinterName"] = selectedPrinter; } 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; } #region 减少闪烁 protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= 0x02000000; return cp; } } #endregion private void btnPlcConfig_Click(object sender, EventArgs e) { this.dgvPlcConfigs.Visible = true; } private void btn_BrowseCatonBtw_Click(object sender, EventArgs e) { using (System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog()) { openFileDialog.Filter = "Bartender 模板文件 (*.btw)|*.btw"; openFileDialog.Title = "请选择 .btw 格式的模板文件"; openFileDialog.Multiselect = false; openFileDialog.RestoreDirectory = true; openFileDialog.CheckFileExists = true; openFileDialog.CheckPathExists = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { string selectedBtwFilePath = openFileDialog.FileName; this.txtBox_containerPath.Text = selectedBtwFilePath; string fileNameOnly = openFileDialog.SafeFileName; CommonMethods.Configxml["BTW_CONFIG"]["ContainerBTWPath"] = this.txtBox_containerPath.Text.Trim(); CommonMethods.WriteXmlFile(CommonMethods.Configxml, CommonMethods.xmlFilePath); } } } private void btn_BrowsePalletBtw_Click(object sender, EventArgs e) { using (System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog()) { openFileDialog.Filter = "Bartender 模板文件 (*.btw)|*.btw"; openFileDialog.Title = "请选择 .btw 格式的模板文件"; openFileDialog.Multiselect = false; openFileDialog.RestoreDirectory = true; openFileDialog.CheckFileExists = true; openFileDialog.CheckPathExists = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { string selectedBtwFilePath = openFileDialog.FileName; this.txtBox_palletpath.Text = selectedBtwFilePath; string fileNameOnly = openFileDialog.SafeFileName; CommonMethods.Configxml["BTW_CONFIG"]["PalletBTWPath"] = this.txtBox_palletpath.Text.Trim(); CommonMethods.WriteXmlFile(CommonMethods.Configxml, CommonMethods.xmlFilePath); } } } private void combox_printer_SelectedIndexChanged(object sender, EventArgs e) { if (combox_printer.SelectedItem != null && combox_printer.SelectedItem.ToString() != "未检测到打印机") { string selectedPrinter = combox_printer.SelectedItem.ToString(); // 移除"(默认)"后缀(如果有),只保存原始打印机名称 selectedPrinter = selectedPrinter.Replace(" (默认)", "").Trim(); CommonMethods.btwConfig.printerName = selectedPrinter; Console.WriteLine($"选中打印机:{selectedPrinter}"); // 保存到配置文件 CommonMethods.Configxml["BTW_CONFIG"]["PrinterName"] = selectedPrinter; CommonMethods.WriteXmlFile(CommonMethods.Configxml, CommonMethods.xmlFilePath); } } } }