In this post I will describe how can we use System.IO.Ports class to listen data coming from external hardware devices, In my next post I will describe how to send data to external devices via serial port or USB.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace ComPortListener
{
public partial class Form1 : Form
{
//Creating newSerial Port Object
private SerialPort port = new SerialPort();
// String container for data
List<String> messages= new List<String>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
/*
GUI oprations, getting data from GUI and setting it into SerialPort object
*/
button2.Enabled = true;
button1.Enabled = false;
// Setting Form GUI values into SerialPort object
port.PortName = TxtPortName.Text.ToString();
port.BaudRate = Convert.ToInt16(TxtbaudRate.Text.ToString());
port.Parity = (Parity)ComboParity.SelectedIndex;
port.DataBits = Convert.ToInt16(TxtDataBits.Text.ToString());
port.StopBits = (StopBits)(ComboStopBits.SelectedIndex);
//Setting flow control or handshake
port.Handshake = (Handshake)(comboFlowControl.SelectedIndex);
port.Open();
}
catch (Exception ex)
{
MessageBox.Show("Port Already open or some other error preventing opening port");
button2.Enabled = false;
button1.Enabled = true;
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string dataReceived =port.ReadExisting();
ListBoxInComingData.Items.Add(dataReceived);
}
void processHeader(String dataReceive)
{
RecID = dataReceive.Substring(29, 15).Trim();
}
private void Form1_Load(object sender, EventArgs e)
{
button2.Enabled = false;
ComboParity.SelectedIndex = 1;
ComboStopBits.SelectedIndex = 1;
comboFlowControl.SelectedIndex = 0;
ListBox.CheckForIllegalCrossThreadCalls = false;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
private void button2_Click(object sender, EventArgs e)
{
port.Close();
button1.Enabled = true;
button2.Enabled = false;
}
}
}