日期:2014-05-17  浏览次数:21286 次

c#怎串口关闭问题
我在父窗口的panel里切换各个子窗口;现在子窗口里有serialpot串口,我现在想在切换子窗口的时候关闭已打开的串口,怎么处理(下面是加载"系统设置"子窗口的代码)
            this.panel1.Controls.Clear();
            系统设置 systemset = new 系统设置();
            systemset.FormBorderStyle = FormBorderStyle.None;
            systemset.TopLevel = false;
            this.panel1.Controls.Add(systemset);
            systemset.Show();
C#

------解决方案--------------------
在this.panel1.Controls.Clear();之前要释放子窗口中使用的串口
//先判断this.panel1中是否含有子控件(实际就是那些子窗口)
如果含有子控件,判断子控件类别,然后将子控件转成子窗口对象,再调用子窗口的关闭串口的方法就行了。
下面以Form1、Form2、Form3作为子窗体,其中Form2使用了串口。
if (this.panel1.Controls.Count > 0)
                {
                    Control ctl = this.panel1.Controls[0];
                    if (ctl is Form1)
                    {
                    }
                    else if (ctl is Form2)
                    {
                        Form2 fmChild = ctl as Form2;
                        fmChild.ClosePort();
                    }