Link to home
Create AccountLog in
Avatar of dannyhop

asked on

Simple example of ComPort usage in C# - C Sharp

I am in need of a simple C# WinFrom with one Command Button ( to send) and one Text Box (to show response).
I need to be able to send a pre defined ASCII string out from COM1 then receive the response and display it tine a text box.
I am having trouble understanding the simplest wway to set up the COM Port.
 - I am Using VS2008

thanks  dannyhop
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Line 36 is the way it is because the DataReceived event is raised on a separate thread, and the ResponseTextBox.Invoke() call executes "ResponseTextBox.Text += response" on the same thread that ResponseTextBox was created on (the main GUI thread), otherwise you'd get an illegal cross-threaded exception.
Or perhaps something like this, which sends a line and expects a line in return:

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;
using System.IO.Ports;

namespace WindowsFormsApplication1
	public partial class Form1 : Form
		private SerialPort comPort;

		public Form1()

			comPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
			comPort.NewLine = "\r";
			comPort.Handshake = Handshake.None;

		private void SendCommandButton_Click(object sender, EventArgs e)

			string response = comPort.ReadLine();
			ResponseTextBox.Text = "Last response: " + response;

Open in new window

Avatar of dannyhop


Thanks for your help.  I think that should do just what i want