using JinYuan.CommunicationLib.Enum; using JinYuan.ControlLib; using JinYuan.Helper; using JinYuan.Models; using JinYuan.VirtualDataLibrary; using Microsoft.Win32; using MiniExcelLibs; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Windows.Forms; using System.Linq; using static Org.BouncyCastle.Math.EC.ECCurve; using System.Drawing; namespace LargeSquareOne { public partial class FrmSystemSet : Form { private string FdConfigFilePath = "fd_config.xlsx"; private List fdConfigs; private List PLCTypes = new List(); private List NGLDTypes1 = new List();//NG拉带类型 private List NGLDTypes2 = new List();//NG拉带类型 private List NGLDTypes3 = new List();//NG拉带类型 private bool isFDEditing = false; private int editingFDRowIndex = -1; //档位 private string Grading1 = "一档"; private string Grading2 = "二档"; private string Grading3 = "三档"; private string Grading4 = "四档"; private string Grading5 = "五档"; private string Grading6 = "六档"; private readonly string configFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config"); /// /// 打印日志方法 /// /// 日志信息 /// 文件夹名字 public static void LogMessage(string Message, string FileName) { string filePath = FileName + "//" + DateTime.Now.ToString("yyyy-MM-dd"); // 日志文件存放路径,默认在debug目录下 string filePath2 = FileName + "//" + DateTime.Now.ToString("yyyy-MM-dd") + "//Mylog.txt";//也可以加上时间 //string file=DateTime.Now+"log.txt"; //检查文件夹是否存在,否则新建 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string logMessage = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}: {Message}";//打印出现的时间 // 将消息写入日志文件 using (StreamWriter writer = new StreamWriter(filePath2, true)) { writer.WriteLine(logMessage); } } 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); this.cmb_PLCType.Items.Add("OmronFinsTcp_HSL"); this.cmb_PLCType.Items.Add("Mitsubishi"); this.cmb_PLCType.Items.Add("Inovance"); FdConfigFilePath = Path.Combine(configFolderPath, "FdConfig.xlsx"); PLCTypes.AddRange(new string[] { "OmronFinsTCP", "OmronCipNet" }); NGLDTypes1.AddRange(new string[] { "面1", "面2", "面3" }); NGLDTypes2.AddRange(new string[] { "面1", "面2", "面3" }); NGLDTypes3.AddRange(new string[] { "面1", "面2", "面3" }); SetupFDDataGridView(); 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_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_OKSwitching.IsChecked = CommonMethods.sysConfig.OKSwitching; 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; InitParam(); } private string devPath = string.Empty; private void InitParam() { this.txt_IP.Text = CommonMethods.plcDevice.IPAddress; this.txt_Prot.Text = CommonMethods.plcDevice.Port.ToString(); this.cmb_PLCType.Text = CommonMethods.plcDevice.PLCType; this.txtFactory_code.Text = CommonMethods.mesConfig.siteCode; this.txtline_No.Text = CommonMethods.mesConfig.lineCode; this.txtEqp_code.Text = CommonMethods.mesConfig.equipNum; } #region 系统相关配置 private void tog_AutoLogin_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveAutoLogin(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改软件自动登录方式:" + ((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, "修改软件自动启动方式:" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void tog_AutoLock_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveAutoLock(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改无操作自动锁屏方式:" + ((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, "修改锁屏间隔时间:" + ((UpDownLabel)sender).CurrentValue.ToString()); CommonMethods.GetSysConfig(); } } private void tog_AutoQieHuanM_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveAutoQieHuanM(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改无操作自动切换监控界面方式:" + ((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, "修改切换监控界面间隔时间:" + ((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, "修改曲线显示数量:" + ((UpDownLabel)sender).CurrentValue.ToString()); CommonMethods.GetSysConfig(); } } private void tog_SwipeCardMode_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveSwipeCardMode(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改刷卡模式:" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); if (CommonMethods.sysConfig.SwipeCardMode && CommonMethods.IsLoginOk) { DialogResult dialogResult1 = new FrmMsgBoxWithAck("当前已登录,是否切换刷卡模式!", "提示").ShowDialog(); if (dialogResult1 == DialogResult.OK) { CommonMethods.AddOPLog(false, $"切换刷卡模式成功,当前用户已注销"); 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.plcDevice.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", "提示").ShowDialog(); return; } if (CommonMethods.plcDevice.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", "提示").ShowDialog(); return; } if (CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改MES/非MES模式切换:" + ((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模式!", "提示").ShowDialog(); if (dialogResult == DialogResult.OK) { CommonMethods.AddOPLog(false, $"关闭MES模式成功,MES用户已注销"); 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参数:" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); } } private void tog_SaveThreadTime_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.SaveSaveThreadTime(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "修改线程耗时日志保存:" + ((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_GroupConfig_Click(object sender, EventArgs e) { new FrmGroupConfig().ShowDialog(); } private void btn_VarConfig_Click(object sender, EventArgs e) { new FrmVariableConfig().ShowDialog(); } private void btn_Sure_Click(object sender, EventArgs e) { bool result = IniConfigHelper.WriteIniData("设备参数", "IP地址", this.txt_IP.Text.Trim(), devPath); IniConfigHelper.WriteIniData("设备参数", "端口号", this.txt_Prot.Text.Trim(), devPath); IniConfigHelper.WriteIniData("设备参数", "PLC类型", this.cmb_PLCType.Text.Trim(), devPath); IniConfigHelper.WriteIniData("MES配置", "工厂代码", this.txtFactory_code.Text.Trim()); IniConfigHelper.WriteIniData("MES配置", "产线编号", this.txtline_No.Text.Trim()); IniConfigHelper.WriteIniData("MES配置", "设备编号", this.txtEqp_code.Text.Trim()); if (result) { CommonMethods.plcDevice.IPAddress = this.txt_IP.Text.Trim(); CommonMethods.plcDevice.Port = Convert.ToInt32(this.txt_Prot.Text.Trim()); CommonMethods.plcDevice.PLCType = cmb_PLCType.Text; CommonMethods.mesConfig.siteCode = this.txtFactory_code.Text.Trim(); CommonMethods.mesConfig.lineCode = this.txtline_No.Text.Trim(); CommonMethods.mesConfig.equipNum = this.txtEqp_code.Text.Trim(); DialogResult dialogResult = new FrmMsgBoxOutWithAck(1, "参数修改成功", "参数设置").ShowDialog(); } else { new FrmMsgBoxOutWithAck(3, "通信参数设置失败", "通信设置").Show(); } } /// /// 取消 /// /// /// private void btn_Cancel_Click(object sender, EventArgs e) { this.txt_IP.Text = CommonMethods.plcDevice.IPAddress; this.txt_Prot.Text = CommonMethods.plcDevice.Port.ToString(); this.cmb_PLCType.Text = CommonMethods.plcDevice.PLCType; 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 tog_OKSwitching_CheckedChanged(object sender, EventArgs e) { if (CommonMethods.plcDevice.IsConnected && CommonMethods.sysConfig.OKSwitching) { CommonMethods.sysConfig.OKSwitching = true; this.tog_OKSwitching.IsChecked = CommonMethods.sysConfig.OKSwitching; CommonMethods.SaveOpenOKModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); new FrmMsgBoxOutWithAck(2, "先停止运行再切换强制OK模式", "提示").ShowDialog(); return; } if (CommonMethods.plcDevice.IsConnected && !CommonMethods.sysConfig.OKSwitching) { CommonMethods.sysConfig.OKSwitching = false; this.tog_OKSwitching.IsChecked = CommonMethods.sysConfig.OKSwitching; CommonMethods.SaveOpenOKModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); new FrmMsgBoxOutWithAck(2, "先停止运行再切换强制OK模式", "提示").ShowDialog(); return; } if (CommonMethods.SaveOpenOKModel(((Toggle)sender).IsChecked)) { CommonMethods.AddOPLog(false, "强制OK/正常NG模式切换:" + ((Toggle)sender).IsChecked.ToString()); CommonMethods.GetSysConfig(); if (CommonMethods.sysConfig.OKSwitching) { CommonMethods.sysConfig.OKSwitching = true; this.tog_OKSwitching.IsChecked = CommonMethods.sysConfig.OKSwitching; CommonMethods.SaveOpenOKModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); } else { DialogResult dialogResult = new FrmMsgBoxWithAck("是否关闭强制OK模式!", "提示").ShowDialog(); if (dialogResult == DialogResult.OK) { CommonMethods.AddOPLog(false, $"关闭强制OK模式成功"); CommonMethods.sysConfig.OKSwitching = false; this.tog_OKSwitching.IsChecked = CommonMethods.sysConfig.OKSwitching; CommonMethods.SaveOpenOKModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); } else { CommonMethods.sysConfig.OKSwitching = true; this.tog_OKSwitching.IsChecked = CommonMethods.sysConfig.OKSwitching; CommonMethods.SaveOpenOKModel(((Toggle)sender).IsChecked); CommonMethods.GetSysConfig(); } } string OKMessage = "调用了强制结果开关,当前状态(true:启用,false:未启用)为: " + CommonMethods.sysConfig.OKSwitching.ToString(); LogMessage(OKMessage, "强制结果OK日志"); } } #region 分档设置 private void LoadFDConfig() { try { if (File.Exists(FdConfigFilePath)) { using (var stream = File.OpenRead(FdConfigFilePath)) { var devices = MiniExcel.Query(stream).ToList(); fdConfigs = devices.Select(device => new FDConfig { FdNum = device.FdNum, OKLD1Type = device.OKLD1Type, OKLD2Type = device.OKLD2Type, OKLD3Type = device.OKLD3Type, OKLD4Type = device.OKLD4Type, OKLD5Type = device.OKLD5Type, OKLD6Type = device.OKLD6Type, //NGLD5Type = device.NGLD5Type, //NGLD6Type = device.NGLD6Type, //NGLD7Type = device.NGLD7Type, IsFDActive = device.IsFDActive, IsNGActive = device.IsNGActive }).ToList(); } } else { fdConfigs = new List(); } RefreshFDDataGridView(); } catch (Exception ex) { MessageBox.Show($"加载配置文件失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); fdConfigs = new List(); } } private void SetColumnsFDReadOnly(bool readOnly) { foreach (DataGridViewColumn col in dgvFdConfigs.Columns) { // PlcNum 列始终保持只读 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.AddRange(new DataGridViewColumn[] { new DataGridViewTextBoxColumn { Name = "FdNum", HeaderText = "分档编号", DataPropertyName = "FdNum", ReadOnly = true, Width = 80, ValueType = typeof(int) }, #region 分档类型 new DataGridViewTextBoxColumn { Name = "OKLD1Type", HeaderText = "OK拉带类型1", DataPropertyName = "OKLD1Type", Width = 120, ValueType = typeof(string) }, new DataGridViewTextBoxColumn { Name = "OKLD2Type", HeaderText = "OK拉带类型2", DataPropertyName = "OKLD2Type", Width = 120, ValueType = typeof(string) }, new DataGridViewTextBoxColumn { Name = "OKLD3Type", HeaderText = "OK拉带类型3", DataPropertyName = "OKLD3Type", Width = 120, ValueType = typeof(string) }, new DataGridViewTextBoxColumn { Name = "OKLD4Type", HeaderText = "OK拉带类型4", DataPropertyName = "OKLD4Type", Width = 120, ValueType = typeof(string) }, new DataGridViewTextBoxColumn { Name = "OKLD5Type", HeaderText = "OK拉带类型5", DataPropertyName = "OKLD5Type", Width = 120, ValueType = typeof(string) }, new DataGridViewTextBoxColumn { Name = "OKLD6Type", HeaderText = "OK拉带类型6", DataPropertyName = "OKLD6Type", Width = 120, ValueType = typeof(string) }, #endregion #region NG拉带类型 // new DataGridViewComboBoxColumn //{ // Name = "NGLD5Type", // HeaderText = "NG拉带类型5", // DataPropertyName = "NGLD5Type",//NG拉带 // DataSource = new List(NGLDTypes1), // 使用新列表避免引用问题 // 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 DataGridViewComboBoxColumn //{ // Name = "NGLD6Type", // HeaderText = "NG拉带类型6", // DataPropertyName = "NGLD6Type",//NG拉带 // DataSource = new List(NGLDTypes2), // 使用新列表避免引用问题 // 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 DataGridViewComboBoxColumn //{ // Name = "NGLD7Type", // HeaderText = "NG拉带类型7", // DataPropertyName = "NGLD7Type",//NG拉带 // DataSource = new List(NGLDTypes3), // 使用新列表避免引用问题 // 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) // 字体设置 // } //}, #endregion #region 开启分档 new DataGridViewCheckBoxColumn { Name = "IsFDActive", HeaderText = "开启分档", DataPropertyName = "IsFDActive", Width = 80, ValueType = typeof(bool), TrueValue = true, FalseValue = false }, new DataGridViewCheckBoxColumn { Name = "IsNGActive", HeaderText = "NG电池不分类排出", DataPropertyName = "IsNGActive", Width = 80, ValueType = typeof(bool), TrueValue = true, FalseValue = false }, #endregion new DataGridViewButtonColumn { Name = "Edit", HeaderText = "操作", Text = "修改", UseColumnTextForButtonValue = true, Width = 80 } }); // 设置列为只读 SetColumnsFDReadOnly(false); // 绑定事件 dgvFdConfigs.CellClick += DgvFdConfigs_CellClick; dgvFdConfigs.CellValidating += DgvFdConfigs_CellValidating; dgvFdConfigs.CellValueChanged += DgvFdConfigs_CellValueChanged; dgvFdConfigs.DataError += DgvFdConfigs_DataError; // 设置自动调整行高 dgvFdConfigs.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; dgvFdConfigs.RowHeadersVisible = false; } 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 "CommConfig": HandleCommFdConfig(fdConfig); break; case "VariableConfig": HandleVariableFdConfig(fdConfig); break; case "Delete": HandleFdDelete(e.RowIndex, fdConfig); break; } } 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 = ""; if (row.Cells["CommConfig"] is DataGridViewButtonCell configCell) configCell.Value = ""; if (row.Cells["Delete"] is DataGridViewButtonCell deleteCell) deleteCell.Value = ""; } } // 禁用添加按钮 //btAddPLC.Enabled = false; } else if (rowIndex == editingFDRowIndex) { // 保存更改 //if (ValidateRow(rowIndex)) { SaveFDChanges(rowIndex); EndFDEditing(); } } } private void EndFDEditing() { isFDEditing = false; editingFDRowIndex = -1; SetColumnsFDReadOnly(true); // 恢复所有按钮文本和状态 foreach (DataGridViewRow row in dgvFdConfigs.Rows) { row.Cells["Edit"].Value = "编辑"; // row.Cells["CommConfig"].Value = "通信组"; // row.Cells["Delete"].Value = "删除"; } // 启用添加按钮 //btAddPLC.Enabled = true; } private void HandleCommFdConfig(FDConfig fdconfig) { } private void HandleVariableFdConfig(FDConfig fdconfig) { } private void HandleFdDelete(int rowIndex, FDConfig fdconfig) { if (MessageBox.Show($"确定要删除 分档 {fdconfig.FdNum} 吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { fdConfigs.RemoveAt(rowIndex); SaveFDConfig(); RefreshFDDataGridView(); } } private void SaveFDChanges(int rowIndex) { try { var row = dgvFdConfigs.Rows[rowIndex]; var config = fdConfigs[rowIndex]; // 更新配置对象 config.OKLD1Type = row.Cells["OKLD1Type"].Value?.ToString() ?? ""; config.OKLD2Type = row.Cells["OKLD2Type"].Value?.ToString() ?? ""; config.OKLD3Type = row.Cells["OKLD3Type"].Value?.ToString() ?? ""; config.OKLD4Type = row.Cells["OKLD4Type"].Value?.ToString() ?? ""; config.OKLD5Type = row.Cells["OKLD5Type"].Value?.ToString() ?? ""; config.OKLD6Type = row.Cells["OKLD6Type"].Value?.ToString() ?? ""; //config.NGLD5Type = row.Cells["NGLD5Type"].Value?.ToString() ?? ""; //config.NGLD6Type = row.Cells["NGLD6Type"].Value?.ToString() ?? ""; //config.NGLD7Type = row.Cells["NGLD7Type"].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); // 保存更改 SaveFDConfig(); MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { // 这里只显示错误信息,不再抛出异常 MessageBox.Show($"保存失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 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 DgvFdConfigs_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; dgvFdConfigs.Rows[e.RowIndex].ErrorText = string.Empty; } private void DgvFdConfigs_DataError(object sender, DataGridViewDataErrorEventArgs e) { e.ThrowException = false; string columnName = dgvFdConfigs.Columns[e.ColumnIndex].HeaderText; MessageBox.Show($"'{columnName}'列的输入数据格式不正确", "数据错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void SaveFDConfig() { try { // 创建备份 if (File.Exists(FdConfigFilePath)) { string backupFile = $"{FdConfigFilePath}.bak"; File.Copy(FdConfigFilePath, backupFile, true); } // Grading1 = fdConfigs[0].OKLD1Type; Grading2 = fdConfigs[0].OKLD2Type; Grading3 = fdConfigs[0].OKLD3Type; Grading4 = fdConfigs[0].OKLD4Type; Grading5 = fdConfigs[0].OKLD5Type; Grading6 = fdConfigs[0].OKLD6Type; SaveFD2xml(); // 直接保存到目标文件 MiniExcel.SaveAs(FdConfigFilePath, fdConfigs, 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 RefreshFDDataGridView() { dgvFdConfigs.DataSource = null; dgvFdConfigs.DataSource = new BindingList(fdConfigs); } private void SaveFD2xml() { CommonMethods.mesConfig.Grading1 = Grading1; CommonMethods.mesConfig.Grading2 = Grading2; CommonMethods.mesConfig.Grading3 = Grading3; CommonMethods.mesConfig.Grading4 = Grading4; CommonMethods.mesConfig.Grading5 = Grading5; CommonMethods.mesConfig.Grading6 = Grading6; //档位 IniConfigHelper.WriteIniData("MES配置", "Grading1", Grading1); IniConfigHelper.WriteIniData("MES配置", "Grading2", Grading2); IniConfigHelper.WriteIniData("MES配置", "Grading3", Grading3); IniConfigHelper.WriteIniData("MES配置", "Grading4", Grading4); IniConfigHelper.WriteIniData("MES配置", "Grading5", Grading5); IniConfigHelper.WriteIniData("MES配置", "Grading6", Grading6); } #endregion } }