ct872587129
智慧土狼
采纳率50%
2018-05-23 03:04 阅读 3.0k

C#多个窗口使用用一个串口接受数据问题

5

我在主窗口MainForm中设置了Static SerialPort,在主界面注册了一个监听事件,然后在调到子界
之前,我注销了监听事件,
serialPort.DataReceived -= new SerialDataReceivedEventHandler(serial_DataReceived);

 然后在子界面Calibration中使用了SerialPort,然后重新设置了监听事件:
 MainForm.serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived2);

想实现的方式是:在子窗口关闭之前将监听事件取消,然后在主界面在重新设置监听事件,关闭子窗口后主界面实现的代码
calibrationForm = new Calibration( );
calibrationForm.ShowDialog();
if (calibrationForm.DialogResult == System.Windows.Forms.DialogResult.OK)
{
serialPort.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
}

但是现在的结果是回到主界面后返回的数据仍然在子窗口事件监听器中显示(通过Console打印返回的数据大小)


求大神指点!!!
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    hxycsdn9159 hxycsdn9159 2018-05-23 03:35

    当然是这样了,关闭子窗体的时候你又没有取消订阅 DataReceived2 这个事件,你搞来搞去一直在关注serial_DataReceived 这个事件
    calibrationForm = new Calibration( );
    calibrationForm.ShowDialog();
    if (calibrationForm.DialogResult == System.Windows.Forms.DialogResult.OK)
    {
    serialPort.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
    serialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceived2); //***************这句代码少了****************
    }

    点赞 评论 复制链接分享
  • wb316 xinyichuba87458088 2018-05-23 03:49

    if (calibrationForm.DialogResult == System.Windows.Forms.DialogResult.OK)
    {
    //要先关闭之前设置的监听
    serialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceived2);
    serialPort.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
    }

    点赞 评论 复制链接分享
  • huachengming huachengming 2018-05-27 00:54

    你在窗体定义串口接受事件,然后顶一个一个事件,show子窗体的时候挂载这个事件,子窗体关闭的时候注销

    子窗体:
    public class Form2 : Form {

            Form1 main;
            public Form2(Form1 mainform)
            {
                main = mainform;
                main.MsgEvent += Mainform_MsgEvent;
            }
    
            private void Mainform_MsgEvent(string obj)
            {
                //do something
    
    
            }
    
            protected override void OnClosing(CancelEventArgs e)
            {
                main.MsgEvent -= Mainform_MsgEvent;
                base.OnClosing(e);
            }
        }
    
                主窗体定义事件
                   System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
        public event Action<string> MsgEvent;
                串口里边触发事件
    
            port.DataReceived += (o, eg) =>
            {
                //解析数据
                var data="":
                MsgEvent?.Invoke(data);
            };
    
    点赞 评论 复制链接分享

相关推荐