// https://youtu.be/Xqx6a_aGlMU
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SerialComm
{
public partial class Form1 : Form
{
System.IO.Ports.SerialPort serialPort = new System.IO.Ports.SerialPort();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] Comlist = System.IO.Ports.SerialPort.GetPortNames();
if(Comlist.Length<1) return ;
comboBox1.Items.AddRange(Comlist) ;
comboBox1.SelectedIndex=0 ;
comboBox2.SelectedIndex=3 ;
comboBox3.SelectedIndex=1 ;
comboBox4.SelectedIndex=0 ;
comboBox5.SelectedIndex=0 ;
}
private void button1_Click(object sender, EventArgs e)
{
if(serialPort.IsOpen) return ;
try
{
serialPort.PortName = comboBox1.Text;
serialPort.BaudRate = int.Parse(comboBox2.Text);
serialPort.DataBits = int.Parse(comboBox3.Text);
serialPort.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), comboBox4.Text, true) ;
serialPort.StopBits = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits),
comboBox5.Text, true) ;
serialPort.Open();
serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceived) ;
button1.BackColor = Color.LightGreen;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
button1.BackColor = Color.Pink;
}
}
private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
const int MaxLen=10000;
byte[] rByte = new byte[MaxLen];
int len = serialPort.Read(rByte, 0, MaxLen);
if(len<=0) return ;
// Cross-thread operation not valid
// TextBox_Add(textBox1, Encoding.Default.GetString(rByte, 0, len));
textBox_Invoke(textBox1, Encoding.Default.GetString(rByte, 0, len)) ; // 받은 데이터는 가공없이 보여준다.
}
private void textBox_Invoke(TextBox tBox, string msg)
{
if(this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate() { TextBox_Add(tBox, msg) ;}));
}
else
TextBox_Add(tBox, msg);
}
private void TextBox_Add(TextBox textBox, string str)
{
textBox.Text += str;
textBox.SelectixxxxxxxxonStart = textBox.Text.Length;
textBox.ScrollToCaret();
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if(!serialPort.IsOpen) return ;
// Enter and Send Line
if(e.KeyChar==(int)Keys.Enter)
{
int lines = textBox2.GetLineFromCharIndex(textBox2.SelectixxxxxxxxonStart);
serialPort.Write(textBox2.Lines[lines] + "\r\n");
}
// Send input immediately
//byte[] sendByte = Encoding.UTF8.GetBytes(e.KeyChar.ToString());
//serialPort.Write(sendByte, 0, 1);
}
}
}