ref C#中的ShowDialog和Show的区别 为什么再ShowDialog中修改变量时原窗口中的变量不会被改变 out如何在这里应用

本文详细对比了模态对话框(showDialog)与非模态窗口(show)的功能差异。模态对话框在打开时会阻止用户与其它窗口交互,直至关闭;而非模态窗口则允许用户在多个窗口间自由切换。此外,还介绍了如何通过代码实现隐藏主窗口并显示模态对话框。
我们可以将show方法转化为showdialog方法 很是不顺手 窗口的顺序也有可能被再次打乱 一但出现问题 而且 那样我们还有花费时间寻找我们要用的窗口 我们往往不喜欢窗口之间的随意切换 比如你在浏览器点击另存为弹出的窗口就是模式窗口 但是他由于未进行绑定 它所显示的各个窗口、对话框是可以相互切换 它是当前唯一(路经打开)为true的 show()仅仅是显示出来窗口界面而已```也就是和你执行的结果在同一窗口显示```所显示的窗口可以在后台运行```而showDialog()是一个对话框窗口界面```执行结果以新窗口界面出现```不允许进行后台运行```就是你想编辑什么的时候```非得先关闭showDialog()窗口界面才可以进行其他操作``` 这就是它们的一点小区别了``` show()是非模式窗体. showDialog()是模式窗体. 区别在于 如果遇到什么问题 所以每个由show方法打开的窗口的顺序是非固定的 而不需要关闭当前窗口、对话框 如果这个时候用Show的话 你可以了解 比如你先打开子窗体 还有一个我个人使用的心得 要等窗体关闭后才能操作其他窗体.而show()则不受此限制. 这是最经常的区别了 由show方法打开的窗口的顺序可能会有很大的改变 ||| 说那么复杂一点用都没有 打开子窗体的同时主窗体又显示出来 则会发生的事情是 想隐藏主窗体 简单代码如下: Form2 f2 = new Form2(); this.Visible = false; f2.ShowDialog(); this.Visible= true; 这就是模态对话框的与Show的区别 ||| 当然有区别..show()是非模式窗体. showDialog()是模式窗体. 第二个下面的窗体是不可修改的.. ||| 简单的说就是在showDialog模式窗体下 最简单的说吧 而使用ShowDialog()的时候主要当子窗体关闭的时候主窗体才会显示 可以用来做逻辑判断 但是showdialog()是有返回值的 以showDialog()打开的窗体 面对多窗口的调用的时候 必须要关闭showDialog模式窗体之后才能对别的进行操作 不能对别的窗体进行操作 show()就是简单的窗体 而show非模式窗口则相反 而show方法由于未进行绑定 你是无法关闭该页面后面的任一页面的 当你没有关闭你当前页的前提下 就是 换言之 他是不可以自由切换的 showdialog是一个进行路经绑定的show方法 顾名思义 那么我们怎么办呢
using EzcadKernel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics.Eventing.Reader; using System.Drawing; using System.Linq; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using static New_AppTest.Form2; namespace New_AppTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } E3_ID m_idEM = E3_ID.INVALID; E3_ID m_idMarker = E3_ID.INVALID; E3_ID m_idCurLayer = E3_ID.INVALID; E3_ID m_idEnt = E3_ID.INVALID; private void Form1_Load(object sender, EventArgs e) { timer1.Start(); E3_ERR Err = EzdKernel.Initial(Application.StartupPath, InitialMode.USB, null); if (Err == E3_ERR.ERR_CLIENTID) { MessageBox.Show("检查板卡ID"); ReadState_btn.Checked = true; ReadState_btn.Enabled = true; ReadState_btn.Text = "卡未链接"; ReadState_btn.ForeColor = Color.Red; return; } else if (Err == E3_ERR.ERR_EZCADRUN) { MessageBox.Show("软件正在运行"); ReadState_btn.Checked = true; ReadState_btn.Enabled = true; ReadState_btn.Text = "重复开启软件"; ReadState_btn.ForeColor = Color.Red; return; } else if (Err == E3_ERR.ERR_NODEVICE) { MessageBox.Show("检查硬件连接"); ReadState_btn.Checked = true; ReadState_btn.Enabled = true; ReadState_btn.Text = "未找到板卡"; ReadState_btn.ForeColor = Color.Red; return; } else { m_idMarker = EzdKernel.E3_MarkerGetFirstValidId(); m_idEM = EzdKernel.E3_CreateEntMgr(0); MarkerID_show.Text = ($"{m_idMarker}"); ReadState_btn.Checked = true; ReadState_btn.Enabled = true; ReadState_btn.Text = "链接成功"; ReadState_btn.ForeColor = System.Drawing.Color.Green; int nLayerIndex = -1;//对图层索引变量进行初始化 EzdKernel.E3_GetCurLayerId(m_idEM, ref m_idCurLayer, ref nLayerIndex);//获取当前图层ID Pt2d pt = new Pt2d();//实例化一个2D对象 pt.X = -10; pt.Y = 0;//对XY的值进行赋值 //对条码信息进行写入 string Text = "Hello!"; EzdKernel.E3_CreateText_2(m_idEM, 0, pt, $"{Text}", 0, 10, 0.5, 0, 1, 0, 0, 0, 0, false, false, false, false, ref m_idEnt); //更新数据 InitialSuccess = true; UpdataShow(); } LisinUsbMarkerState(); } private void UpdataShow() { double dwidth = 100; double dheight = 100; int nwidth = pictureBox1.Width; int nheight = pictureBox1.Height; double dScalel1 = dwidth / nwidth; double dScalel2 = dheight / nheight; double sfe = 0; if (dScalel1 < dScalel2) { sfe = dScalel2; } else { sfe = dScalel1; } double dLBX = -0.5 * sfe * nwidth; double dLBY = -0.5 * sfe * nheight; Bitmap bitmap = new Bitmap(nwidth, nheight); Graphics g = Graphics.FromImage(bitmap); g.Clear(Color.Gray); IntPtr hdc = g.GetHdc(); //在指定窗口绘制数据库中图像的预览图, //参数包括 hdc 对应图层的句柄;要显示图层的ID;默认为0;窗口的像素宽度与高度;窗口左下角XY方向的逻辑坐标;窗口的逻辑尺寸与对应比例 EzdKernel.E3_DrawEnt2(hdc, m_idCurLayer, 0, nwidth, nheight, dLBX, dLBY, sfe); g.ReleaseHdc(); pictureBox1.Image = Image.FromHbitmap(bitmap.GetHbitmap()); pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; } #region usb监听功能 /// <summary> /// 根据系统的端口窗体的提示来获取USB链接状态的监听,将系统弹窗事件句柄传递给Ez的监听的API /// </summary> /// <returns></returns> //获取窗口的句柄定义的API接口,系统弹窗 [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetForegroundwindow(); public class USB_Message { public const int USER = 0x0400;//消息偏移基值 //发现掉卡 public const int WM_LOST = USER + 17; //发现新卡 public const int WM_GETNEW = USER + 18; public const int WM_CHANGE = 537; } protected void DefwndProc(ref Message m) { switch (m.Msg) { case USB_Message.WM_LOST: { Console.WriteLine("发现掉卡"); ReadState_btn.Checked = true; break; } case USB_Message.WM_GETNEW: { Console.WriteLine("发现新卡"); EzdKernel.E3_MarkerUsbMonitorGetNewDevice(ref m_idMarker); break; } default: break; } } private void LisinUsbMarkerState() { IntPtr hWndLising = EzdKernel.GetForegroundWindow(); //开启USB监听功能以后需要把刚才得到的窗体句柄传进去 EzdKernel.E3_MarkerInitUsbMonitor2(hWndLising); } #endregion private void Colose_btn_Click(object sender, EventArgs e) { if (m_idMarker != 0) { E3_ERR Err = EzdKernel.E3_CloseMarker(m_idMarker); InitialReadStatebtn(); MarkerID_show.Clear(); EzdKernel.E3_FreeEntity(m_idEnt); MessageBox.Show($"打标卡{m_idMarker}成功关闭"); return; } else { MessageBox.Show($"未找到板卡ID为{m_idMarker}的板卡"); ReadState_btn.Checked = true; ReadState_btn.Enabled = true; ReadState_btn.Text = "卡未链接"; ReadState_btn.ForeColor = Color.Red; } } private void InitialReadStatebtn()//初始化状态显示 { ReadState_btn.Enabled = false; ReadState_btn.Checked = false; ReadState_btn.Text = "状态显示"; } #region IO监视功能 /// <summary> /// 通过该接口接收一个ref变量,将这个变量的值转变成二进制数,然后通过一个循环对io的数量进行 /// 遍历,同需要在for循环里嵌套一个foreach遍历方法,这个是遍历的是显示控件的名字索引。同在这个 /// 遍历函数里边通过对传入值与K左移相应位数做位与运算与K的值做对比,相等则说明对应IO口是导通状态 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { m_idMarker = EzdKernel.E3_MarkerGetFirstValidId(); m_idEM = EzdKernel.E3_CreateEntMgr(0); InitIOCheckBox(); ushort uInputData = 0; EzdKernel.E3_MarkerReadPort(m_idMarker, ref uInputData); for (int i = 0; i < 5; i++) { int k = 1 << i; foreach (Control b in groupBox3.Controls) { if (b is CheckBox) { if (b.Name == "Input_Btn" + i) { CheckBox currentCheckBox = (CheckBox)b;//进行了强制转换,将control类型的b强制转换成了checkbox类型 if ((uInputData & k) == k) { currentCheckBox.Checked = true; } else { currentCheckBox.Checked = false; currentCheckBox.Enabled = false; } } } } } ushort uOUTputData = 0; EzdKernel.E3_MarkerGetWritePort(m_idMarker, ref uOUTputData); for (int i = 0; i < 5; i++) { int k = 1 << i; foreach (Control c in groupBox4.Controls) { if (c is CheckBox) { if (c.Name == "output_btn" + i) { CheckBox currentCheckBox = (CheckBox)c;//进行了强制转换,将control类型的b强制转换成了checkbox类型 if ((uInputData & k) == k) { currentCheckBox.Checked = true; } else { currentCheckBox.Checked = false; currentCheckBox.Enabled = false; } } } } } } private void InitIOCheckBox() { foreach (Control b in groupBox3.Controls) { if (b is CheckBox) { CheckBox currentCheckBox = (CheckBox)b; currentCheckBox.Enabled = false; } break; } foreach (Control c in groupBox4.Controls) { if (c is CheckBox) { CheckBox currentCheckBox = (CheckBox)c; currentCheckBox.Enabled = false; } break; } #endregion } MarkEntMode m_Build = MarkEntMode.StaticMark; private void MarkerStatic_btn_CheckedChanged(object sender, EventArgs e) { if (Markercon_btn.Checked || ChoseMarker_btn.Checked) { m_Build = MarkEntMode.StaticMark; } else { MarkerStatic_btn.Checked = false; MessageBox.Show("请选择加工对象!"); } } private void RadLight_btn_CheckedChanged(object sender, EventArgs e) { if (RadLight_btn.Checked) { m_Build = MarkEntMode.RedLight; } } private void Markercon_btn_CheckedChanged(object sender, EventArgs e) { if (Markercon_btn.Checked) { m_Build = MarkEntMode.StaticMark; } } private void ChoseMarker_btn_CheckedChanged(object sender, EventArgs e) { if (ChoseMarker_btn.Checked) { m_Build = MarkEntMode.StaticMark; } } private void Work() { if (backgroundWorker1.IsBusy) { return; } backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string std = string.Empty; string str = string.Empty; str = "RedLight is Working!"; string ser = "激光加工中"; if (m_Build == MarkEntMode.RedLight) { EzdKernel.E3_MarkerSwitchRedLight(m_idMarker, true); backgroundWorker1.ReportProgress(0, str); Thread.Sleep(10000); if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; } } //用于红光显示轮廓 E3_ERR Err = EzdKernel.E3_MarkerMarkEnt2(m_idMarker, m_idEM, m_idCurLayer, m_Build, 0, 0); if (Err == E3_ERR.ERR_USER_STOP) { if (m_Build == MarkEntMode.RedLight) { EzdKernel.E3_MarkerSwitchRedLight(m_idMarker, false); backgroundWorker1.ReportProgress(0, std); if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; } } } if (m_Build == MarkEntMode.StaticMark && MarkerStatic_btn.Checked) { EzdKernel.E3_MarkerLaserOn(m_idMarker, 1, true); backgroundWorker1.ReportProgress(0, ser); Thread.Sleep(2000); if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; } } else { MessageBox.Show("标刻失败,检查标刻设置"); backgroundWorker1.CancelAsync(); if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; } return; } } public static int UnUserStop1() { int a = 10; return a; } public static int UnUserStop2() { int a = 20; return a; } public delegate int RunStop(); //回调函数 public static int RunDataStop(RunStop vb) { return vb.Invoke(); } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { string str = e.UserState.ToString(); this.label7.Text = str; } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.label7.Text = string.Empty; if (e.Cancelled) { int result = RunDataStop(UnUserStop1); EzdKernel.E3_MarkerLaserOn(m_idMarker, 1, false); MessageBox.Show($"用户停止了加工,返回值为{result}"); } else { int result = RunDataStop(UnUserStop2); EzdKernel.E3_MarkerLaserOn(m_idMarker, 1, false); MessageBox.Show($"加工完成,返回值为{result}"); } } private void MarkerStar_btn_Click(object sender, EventArgs e) { Work(); } private void MarkerStop_btn_Click(object sender, EventArgs e) { E3_ERR Err = EzdKernel.E3_MarkerStop(m_idMarker); //if (backgroundWorker1.IsBusy && !backgroundWorker1.WorkerSupportsCancellation) if (Err == E3_ERR.ERR_ERRORPARAM && backgroundWorker1.IsBusy) { backgroundWorker1.CancelAsync(); this.label7.Text = "正在停止……"; } else { this.label7.Text = string.Empty; } } private void toolStripMenuItem2_Click(object sender, EventArgs e) { OpenFileDialog ofr = new OpenFileDialog(); ofr.Filter = "Ez3(.ez3)|*.ez3"; if (ofr.ShowDialog() == DialogResult.OK) { E3_ERR Err = EzdKernel.E3_OpenFileToEntMgr(ofr.FileName, m_idEM, false, false); int nCuarLayerIndex = -1; EzdKernel.E3_GetCurLayerId(m_idEM, ref m_idCurLayer, ref nCuarLayerIndex); EzdKernel.E3_FindEntInLayerByIndex(m_idCurLayer, 0, ref m_idEnt); UpdataShow(); } } private void toolStripMenuItem3_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog(); save.Filter = "EZ3(.ez3)|*.ez3"; save.AddExtension = true; save.OverwritePrompt = true; if (save.ShowDialog() == DialogResult.OK) { E3_ERR Err = EzdKernel.E3_SaveEntMgrToFile(Application.StartupPath, m_idEM, false, false, "", "", ""); if (Err != E3_ERR.ERR_SUCCESS) { MessageBox.Show($"文件保存成功{Application.StartupPath}"); } } } bool InitialSuccess = false; private void AddText_btn_Click(object sender, EventArgs e) { if (InitialSuccess) { Pt2d pt = new Pt2d();//实例化一个2D对象 pt.X = -10; pt.Y = 0;//对XY的值进行赋值 //对条码信息进行写入 string TX = Textinput.Text; EzdKernel.E3_CreateText_2(m_idEM, 0, pt, $"{TX}", 0, 10, 0.5, 0, 1, 0, 0, 0, 0, false, false, false, false, ref m_idEnt); //更新数据 UpdataShow(); return; } } private void FixText_btn_Click(object sender, EventArgs e) { if (InitialSuccess && Textinput.Text != null) { EzdKernel.E3_ChangeTextById(m_idEnt, Textinput.Text); //更新数据 UpdataShow(); return; } } private void textBox1_TextChanged(object sender, EventArgs e) { this.textBox1.Text = comboBox1.Text; } private void toolStripMenuItem4_Click(object sender, EventArgs e) { bool bReturnOK = false; E3_ERR Err = EzdKernel.E3_MarkerDlgSetCfg(m_idMarker, ref bReturnOK); } private void Stoping_btn_Click(object sender, EventArgs e) { E3_ERR Err = EzdKernel.E3_MarkerStop(m_idMarker); if (Err == E3_ERR.ERR_ERRORPARAM && backgroundWorker1.IsBusy) { backgroundWorker1.CancelAsync(); this.label7.Text = "正在停止……"; } else { this.label7.Text = string.Empty; } } //在这个窗口创建一个list类型的全局变量,用来承接窗口2传递过来的笔的参数 public List<PenInfo> allPenParam=new List<PenInfo>(); public Dictionary<Keys,ValueTuple> allDict=new Dictionary<Keys,ValueTuple>(); private void PenList_btn_Click(object sender, EventArgs e) { Form2 formtwo = new Form2(); formtwo.Show(); formtwo.OnSendDate += Form2_ItemsChanged;//注册OnSendDate事件函数执行函数 formtwo.FormClosed += (s, args) => formtwo=null;//释放资源 } private void Form2_ItemsChanged(object sender, PenGotoMianForm e) { // 跨线程安全更新 UI(非模态窗口可能触发跨线程) if (comboBox1.InvokeRequired) { allPenParam = e.InPutDate; comboBox1.Invoke(new Action(() => UpdateComboBox(allPenParam))); } else { allPenParam = e.InPutDate; UpdateComboBox(allPenParam); } } private void UpdateComboBox(List<PenInfo> items) { comboBox1.Items.Clear(); comboBox1.Items.AddRange(items.ToArray()); if (comboBox1.Items.Count > 0) { comboBox1.SelectedIndex = 0; } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { EzdKernel.E3_CloseMarker(m_idMarker); EzdKernel.E3_FreeEntMgr(m_idEM); EzdKernel.E3_Close(); } private void 打开校正ToolStripMenuItem_Click(object sender, EventArgs e) { Form3 formthree= new Form3(); formthree.Show(); } private void 是否使用校正文件ToolStripMenuItem_Click(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } public void LoadPenparma() { foreach (var item in allPenParam) { textBox1.Text= item.PenNo.ToString(); textBox2.Text= item.dPowerRatio.ToString(); textBox3.Text= item.dMarkSpeed.ToString(); textBox4.Text=item.dFreq.ToString(); } } private void OK_btn_Click(object sender, EventArgs e) { LoadPenparma(); } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { int nCuontLayerIndex = -1; int nCuontLayer = 0; EzdKernel.E3_GetLayerCount(m_idEM, ref nCuontLayer, ref nCuontLayerIndex); if (nCuontLayerIndex > 0) { for (int i = 0; i < nCuontLayerIndex; i++) { comboBox2.Items.Add(i.ToString()); } } comboBox2.SelectedIndex = nCuontLayerIndex; } private void EXIT_btn_Click(object sender, EventArgs e) { textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); } } } 这是窗口1的代码using EzcadKernel; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static New_AppTest.Form2; using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace New_AppTest { public partial class Form2 : Form { public event EventHandler<PenGotoMianForm> OnSendDate;//封装了一个PenGotoMianForm的类,触发函数是OnSendDate // 存储元素集合 private List<PenInfo> _currentItems = new List<PenInfo>();//实例化一个list的对象用来承接元素 public Form2() { InitializeComponent(); } E3_ID m_idEM = E3_ID.INVALID; E3_ID m_idMarker = E3_ID.INVALID; E3_ID m_idCurLayer = E3_ID.INVALID; E3_ID m_idEnt = E3_ID.INVALID; StringBuilder pStrName = new StringBuilder(256); int clr = 0; bool bDisableMark = false; bool bUseDefParam = false; double dPowerRatio = 10; double dQPulseWidth = 10; int nMarkLoop = 0; double dMarkSpeed = 1000; double dCurrent = 1; double dFreq = 10000; double dJumpSpeed = 4000; int nMinJumpDelayTCUs = 10; int nMaxJumpDelayTCUs = 80; int nStartTC = 100; int nLaserOffTC = 100; int nEndTC = 100; int nPolyTC = 100; double dJumpLengthLimit = 10; double dPointTimeMs = 10; bool nSpiSpiContinueMode = false; int nSpiWave = 0; int nYagMarkMode = 0; bool bPulsePointMode = false; int nPulseNum = 0; bool bEnableACCMode = false; double dEndComp = 0; double dAccDist = 0; double dBreakAngle = 0; bool bWobbleMode = false; double bWobbleDiameter = 0; double bWobbleDist = 0; private void button1_Click(object sender, EventArgs e) { var nSelectedPen1 = comboBox1.SelectedItem; if (flag == true && nSelectedPen1 != null) { int nSelectedPen = comboBox1.SelectedIndex; clr = int.Parse(textBox2.Text); bDisableMark = bool.Parse(textBox3.Text); bUseDefParam = bool.Parse(textBox4.Text); //StringBuilder strParamName = new StringBuilder(textBox5.Text); string strParamName = (string)(textBox5.Text); nMarkLoop = int.Parse(textBox6.Text); dMarkSpeed = double.Parse(textBox7.Text); dFreq = double.Parse(textBox8.Text); dPowerRatio = double.Parse(textBox9.Text); dQPulseWidth = double.Parse(textBox10.Text); nStartTC = int.Parse(textBox11.Text); nLaserOffTC = int.Parse(textBox12.Text); nPolyTC = int.Parse(textBox13.Text); nEndTC = int.Parse(textBox14.Text); dJumpSpeed = double.Parse(textBox15.Text); nMinJumpDelayTCUs = int.Parse(textBox16.Text); nMaxJumpDelayTCUs = int.Parse(textBox17.Text); dJumpLengthLimit = double.Parse(textBox18.Text); E3_ERR Err = EzdKernel.E3_SetPenParam(m_idEM, nSelectedPen, strParamName, clr, bDisableMark, bUseDefParam, nMarkLoop, dMarkSpeed, dPowerRatio, dCurrent, dFreq, dQPulseWidth, nStartTC, nLaserOffTC, nEndTC, nPolyTC, dJumpSpeed, nMinJumpDelayTCUs, nMaxJumpDelayTCUs, dJumpLengthLimit, dPointTimeMs, nSpiSpiContinueMode, nSpiWave, nYagMarkMode, bPulsePointMode, nPulseNum, bEnableACCMode, dEndComp, dAccDist, dBreakAngle, bWobbleMode, bWobbleDiameter, bWobbleDist); PenInfo pen = new PenInfo() { #region 笔的各个参数 PenNo = nSelectedPen, clr = clr, bWobbleMode=bWobbleMode, bWobbleDiameter=bWobbleDiameter, bWobbleDist=bWobbleDist, nSpiWave = nSpiWave, nYagMarkMode= nYagMarkMode, bPulsePointMode= bPulsePointMode, nPulseNum= nPulseNum, dBreakAngle= dBreakAngle, dAccDist = dAccDist, bEnableACCMode = bEnableACCMode, dEndComp= dEndComp, nSpiSpiContinueMode = nSpiSpiContinueMode, dJumpLengthLimit = dJumpLengthLimit, dPointTimeMs= dPointTimeMs, bDisableMark =bDisableMark, bUseDefParam=bUseDefParam, nMarkLoop = nMarkLoop, dMarkSpeed = dMarkSpeed, dPowerRatio = dPowerRatio, dCurrent = dCurrent, dFreq = dFreq, dQPulseWidth = dQPulseWidth, nStartTC = nStartTC, nEndTC = nEndTC, nLaserOffTC = nLaserOffTC, dJumpSpeed = dJumpSpeed, nMinJumpDelayTCUs = nMinJumpDelayTCUs, nMaxJumpDelayTCUs= nMaxJumpDelayTCUs, #endregion }; foreach (var item in checkedListBox1.Items) { if (item is PenInfo penItem) { if (nSelectedPen == penItem.PenNo) { MessageBox.Show("笔号输入重复"); return; } } } checkedListBox1.Items.Add(pen); } else { MessageBox.Show("先选择并加载笔号!"); return; } } /// <summary> /// 这里的更新数据用来承接控件checkedListBox1内部的元素将里边所有的元素放到 /// list泛型_currentItems中去,通过触发事件函数来将_currentItems中的值传递到父类窗口 /// 的combox中去 /// </summary> private void UpdateItems()//触发事件的函数实现 { _currentItems.Clear(); // 收集选中的元素 for ( int index=0;index<checkedListBox1.Items.Count;index++) { if (checkedListBox1.GetItemChecked(index)) { var item = checkedListBox1.Items[index]; if (item is PenInfo pen) { _currentItems.Add(pen); } } } // 通知 Form1 元素已变化(触发事件) OnSendDate?.Invoke(this,new PenGotoMianForm(_currentItems)); } bool flag = false; private void button2_Click_1(object sender, EventArgs e) { flag = true; foreach (int index in checkedListBox1.CheckedIndices) { int nSelectedPen = index; EzdKernel.E3_GetPenParam(m_idEM, nSelectedPen, pStrName, ref clr, ref bDisableMark, ref bUseDefParam, ref nMarkLoop, ref dMarkSpeed, ref dPowerRatio, ref dCurrent, ref dFreq, ref dQPulseWidth, ref nStartTC, ref nLaserOffTC, ref nEndTC, ref nPolyTC, ref dJumpSpeed, ref nMinJumpDelayTCUs, ref nMaxJumpDelayTCUs, ref dJumpLengthLimit, ref dPointTimeMs, ref nSpiSpiContinueMode, ref nSpiWave, ref nYagMarkMode, ref bPulsePointMode, ref nPulseNum, ref bEnableACCMode, ref dEndComp, ref dAccDist, ref dBreakAngle, ref bWobbleMode, ref bWobbleDiameter, ref bWobbleDist); textBox2.Text = clr.ToString(); textBox3.Text = bDisableMark.ToString(); textBox4.Text = bUseDefParam.ToString(); textBox5.Text = pStrName.ToString(); textBox6.Text = nMarkLoop.ToString(); textBox7.Text = dMarkSpeed.ToString(); textBox8.Text = dFreq.ToString(); textBox9.Text = dPowerRatio.ToString(); textBox10.Text = dQPulseWidth.ToString(); textBox11.Text = nStartTC.ToString(); textBox12.Text = nLaserOffTC.ToString(); textBox13.Text = nPolyTC.ToString(); textBox14.Text = nEndTC.ToString(); textBox15.Text = dJumpSpeed.ToString(); textBox16.Text = nMinJumpDelayTCUs.ToString(); textBox17.Text = nMaxJumpDelayTCUs.ToString(); textBox18.Text = dJumpLengthLimit.ToString(); } int nSelectedPen1 =checkedListBox1.Items.Count; int nSelate = checkedListBox1.Items.Count; if (nSelate == 0 && comboBox1.Text == null) { return; } EzdKernel.E3_GetPenParam(m_idEM, nSelectedPen1, pStrName, ref clr, ref bDisableMark, ref bUseDefParam, ref nMarkLoop, ref dMarkSpeed, ref dPowerRatio, ref dCurrent, ref dFreq, ref dQPulseWidth, ref nStartTC, ref nLaserOffTC, ref nEndTC, ref nPolyTC, ref dJumpSpeed, ref nMinJumpDelayTCUs, ref nMaxJumpDelayTCUs, ref dJumpLengthLimit, ref dPointTimeMs, ref nSpiSpiContinueMode, ref nSpiWave, ref nYagMarkMode, ref bPulsePointMode, ref nPulseNum, ref bEnableACCMode, ref dEndComp, ref dAccDist, ref dBreakAngle, ref bWobbleMode, ref bWobbleDiameter, ref bWobbleDist); textBox2.Text = clr.ToString(); textBox3.Text = bDisableMark.ToString(); textBox4.Text = bUseDefParam.ToString(); textBox5.Text = pStrName.ToString(); textBox6.Text = nMarkLoop.ToString(); textBox7.Text = dMarkSpeed.ToString(); textBox8.Text = dFreq.ToString(); textBox9.Text = dPowerRatio.ToString(); textBox10.Text = dQPulseWidth.ToString(); textBox11.Text = nStartTC.ToString(); textBox12.Text = nLaserOffTC.ToString(); textBox13.Text = nPolyTC.ToString(); textBox14.Text = nEndTC.ToString(); textBox15.Text = dJumpSpeed.ToString(); textBox16.Text = nMinJumpDelayTCUs.ToString(); textBox17.Text = nMaxJumpDelayTCUs.ToString(); textBox18.Text = dJumpLengthLimit.ToString(); } private void button3_Click_1(object sender, EventArgs e) { if (checkedListBox1.CheckedIndices.Count == 0) { MessageBox.Show("没有可删除项!"); return; } else { for (int ter = checkedListBox1.CheckedIndices.Count - 1; ter >= 0; ter--) { int selectedIndex = checkedListBox1.CheckedIndices[ter]; checkedListBox1.Items.RemoveAt(selectedIndex); } } } private void Form2_Load(object sender, EventArgs e) { //LoadCheckedItemsFromJson(); } private void Form2_FormClosed(object sender, FormClosedEventArgs e) { } private void EntDate_btn_Click(object sender, EventArgs e) { UpdateItems(); } private void SavePenSettings() { // 1. 获取当前笔号+参数(之前逻辑一致) var currentPen = new PenSetting { PenId = checkedListBox1.CheckedItems.Count, Params = new Dictionary<string, object> { { "Color", textBox2.Text }, { "DisableMark", textBox3.Text}, { "UseDefParam",textBox4.Text }, { "StrName", textBox5.Text }, { "MarkLoop", textBox6.Text }, { "MarkSpeed", textBox7.Text }, { "Freq", textBox8.Text }, { "PowerRatio",textBox9.Text }, { "QPulseWidth",textBox10.Text }, { "StartTC", textBox11.Text }, { "LaserOffTC", textBox12.Text }, { "PolyTC", textBox13.Text }, { "EndTC", textBox14.Text }, { "JumpSpeed", textBox15.Text }, { "MinJumpDelayTCUs",textBox16.Text }, { "MaxJumpDelayTCUs", textBox17.Text }, { "JumpLengthLimit", textBox18.Text }, } }; List<PenSetting> allPens = new List<PenSetting>();// 2. 读取已保存的笔号列表(用Newtonsoft.Json反序列化) string filePath = "D:\\C#_Data\\New_AppTest\\PenSettings.json"; if (File.Exists(filePath)) { string json = File.ReadAllText(filePath); allPens = JsonConvert.DeserializeObject<List<PenSetting>>(json); // 替换为JsonConvert } // 3. 替换/新增笔号(逻辑不变) var existingPen = allPens.FirstOrDefault(p => p.PenId == currentPen.PenId); if (existingPen != null) allPens.Remove(existingPen); allPens.Add(currentPen); // 4. 写入JSON文件(用Newtonsoft.Json序列化) string newJson = JsonConvert.SerializeObject(allPens, Formatting.Indented); // 替换为JsonConvert File.WriteAllText(filePath, newJson); } public readonly string _JsonPath = "D:\\C#_Data\\New_AppTest\\PenSettings.json"; private void LoadCheckedItemsFromJson() { try { // 检查文件是否存在 if (!File.Exists(_JsonPath)) { MessageBox.Show($"JSON文件不存在:{_JsonPath}\n将创建空文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); // 创建空文件(避免后续报错) File.WriteAllText(_JsonPath, JsonConvert.SerializeObject(new List<CheckedListItem>())); return; } // 读取JSON文件内容 string jsonContent = File.ReadAllText(_JsonPath); // 反序列化为选中项列表 List<CheckedListItem> checkedItems = JsonConvert.DeserializeObject<List<CheckedListItem>>(jsonContent) ?? new List<CheckedListItem>(); // 清空控件并填充数据 checkedListBox1.Items.Clear(); foreach (var item in checkedItems) { // 添加项并设置选中状态 int index = checkedListBox1.Items.Add(item.Text); checkedListBox1.SetItemChecked(index, item.IsChecked); } } catch (JsonException ex) { MessageBox.Show($"JSON格式错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (IOException ex) { MessageBox.Show($"文件读写错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show($"加载失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void SaveParam_btn_Click(object sender, EventArgs e) { SavePenSettings(); } } } 这是窗口2的代码,窗口2的PenInfo参数传递到了窗口1,现在要实现在窗口1中的Combobox选择笔号以后,textbox控件内容随笔号不同而有不同的显示
最新发布
12-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值