C#运行串行端口数据接收事件处理程序以另一种形式

时间:2018-10-23 07:26:52

标签: c#

在我的form1中,我有serialPort1,我想将serialPort1_DataRecieved运行到另一种形式。 或使用form1串行端口将数据接收的处理程序创建为form2。

我正在使用此代码将串行端口传递给另一种形式。

 FOrm1 f1= new Form1(serialPort1);
 f1.Show();

这就是我想要在Form2中尝试做的事情

    SerialPort serialPort2;
    public delegate void myDelegate(string sData);
    public Form2(SerialPort SP)
    {
        InitializeComponent();
        serialPort2 = SP;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        try
        {
            serialPort2.Open();
            serialPort2.DataReceived += port_OnReceiveData;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }
   publicstatic void port_OnReceiveData(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {

        string sData;
        serialPort2.ReadTimeout = 20;

        try
        {
            sData = serialPort2.ReadLine();
            this.BeginInvoke((new myDelegate(Text_Out)), sData);
        }


        catch (Exception ex)
        {
        }

    }

我这样做可以解决我的问题

2 个答案:

答案 0 :(得分:0)

我解决了这个问题

    SerialPort serialPort2;
    public delegate void myDelegate(string sData);
    public Form2(SerialPort SP)
    {
        InitializeComponent();
        serialPort2 = SP;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        try
        {
            serialPort2.Open();
            serialPort2.DataReceived += port_OnReceiveData;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }
   publicstatic void port_OnReceiveData(object sender, 
   System.IO.Ports.SerialDataReceivedEventArgs e)
    {

        string sData;
        serialPort2.ReadTimeout = 20;

        try
        {
            sData = serialPort2.ReadLine();
            this.BeginInvoke((new myDelegate(Text_Out)), sData);
        }


        catch (Exception ex)
        {
        }

    }

答案 1 :(得分:-1)

这样做:只需在窗体2上创建接口,然后在窗体1中继承它,并将窗体1设置为窗体2的接口,然后从窗体2,窗体2调用接口中的方法

  public partial class Form2 : Form
    {
        public interface ABC
        {
             void OK(string data);
        }

        public ABC abc { get; set; } 

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            abc.OK("hi");
        }
    }

以您的表格1

 public partial class Form1 : Form,ABC
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.abc = this;
            f.Show();

        }

        public void OK(string data)
        {
            throw new NotImplementedException();
        }
    }