为什么dataReceived事件不起作用?

时间:2016-04-19 08:28:30

标签: c# visual-studio

我的串口接收数据有问题。

在我班上:

class Connection
{
    SerialPort Port = new SerialPort();

    public void ConfigurePort( string name, int speed)
    {
        Port.PortName = name;
        Port.BaudRate =  speed;
        Port.DataBits = 8;
        Port.Parity = Parity.None;
        Port.StopBits = StopBits.One;
        Port.Encoding = Encoding.BigEndianUnicode;
        Port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        Port.RtsEnable = true;

    }

   public void Write()
    {
        Port.Write("TAD->TIC,LIST");   
    }

    public void OpenPort()
    {
        try
        {
        Port.Open();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString(),"Error",  MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

    }

    public void ClosePort()
    {
        try
        {
            Port.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    public static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
    }

}

在我的Form1中:

 private void XXX_Load(object sender, EventArgs e)
    {
        port.ConfigurePort("COM5", 115200); 
    }


 private void button2_Click(object sender, EventArgs e)
    {
        port.OpenPort();
        port.Write();
        port.ClosePort();
    }

为什么单击按钮事件后DataReceivedHandler不起作用?  当代码在主文件中时,一切正常。

0 个答案:

没有答案