コード例 #1
0
    /// <summary>
    /// 使用事件觸發方式來實現串口數據的讀取
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        byte[] Resoursedata = new byte[serialPort.BytesToRead];
        int    count        = serialPort.Read(Resoursedata, 0, Resoursedata.Length);//在此就可以讀取到當前緩衝區內的數據

        //執行數據操作
        serialPort.DiscardInBuffer();  //丟棄傳輸緩衝區數據
        serialPort.DiscardOutBuffer(); //每次丟棄接收緩衝區的數據
        if (count > 0)
        {
            if (SerialPortMessageEvent != null && SerialPortMessageEvent.GetInvocationList().Length > 0) // If somebody is listening
            {
                SerialPortMessageEvent.Invoke(Resoursedata);                                             // Invoke方法防止主線程擁堵衝突
            }
        }
    }
コード例 #2
0
 private void ListenSerialPort()
 {
     while ((serialPort.IsOpen == true))
     {
         try
         {
             int bufferSize = serialPort.ReadBufferSize;
             //
             byte[] buf   = new byte[bufferSize];
             int    count = serialPort.Read(buf, 0, bufferSize);
             if (count > 0)
             {
                 if (SerialPortMessageEvent != null && SerialPortMessageEvent.GetInvocationList().Length > 0) // If somebody is listening
                 {
                     SerialPortMessageEvent.Invoke(buf);
                 }
             }
         }
         catch (System.Exception)
         {
         }
     }
 }