using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports; // RS232통신(시리얼통신) IO.Ports 활성화
namespace Form1.cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
COM_port.DataSource = SerialPort.GetPortNames();
}
// 연결 버튼
private void connect_Click(object sender, EventArgs e)
{
if(!serialPort1.IsOpen) // 시리얼포트가 열려 있지 않으면
{
serialPort1.PortName = COM_port.Text; // 콤보박스의 선택된 COM포트명을 시리얼포트명으로 지정
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Parity = Parity.None;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); // 이것이 꼭 필요하다.
serialPort1.Open(); // 시리얼포트 열기
connection_status.Text = "포트가 열렸습니다.";
connection_status.ForeColor = Color.Green;
}
else // 시리얼 포트가 열려 있으면
{
connection_status.Text = "포트가 이미 열려 있습니다.";
connection_status.ForeColor = Color.Blue;
}
}
// 해제 버튼
private void disconnect_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen) // 시리얼포트가 열려 있으면
{
serialPort1.Close(); // 시리얼포트 닫기
connection_status.Text = "포트가 닫혔습니다.";
connection_status.ForeColor = Color.Red;
}
else // 시리얼포트가 닫혀 있으면
{
connection_status.Text = "포트가 닫혀 있습니다.";
connection_status.ForeColor = Color.Blue;
}
}
private void connection_status_Click(object sender, EventArgs e)
{
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(MySerialReceived));
}
private void MySerialReceived(object s, EventArgs e)
{
try
{
int iRecSize = serialPort1.BytesToRead; // 수신된 데이터 갯수
if (iRecSize != 0) // 수신된 데이터의 수가 0이 아닐때만 처리하자
{
byte[] buff = new byte[iRecSize];
try
{
serialPort1.Read(buff, 0, iRecSize);
txbRXText.AppendText(System.Text.Encoding.UTF8.GetString(buff, 0, buff.Length));
// 텍스트를 추가하겠다.
}
catch { }
}
}
catch (System.Exception) { }
}
private void txbRXText_TextChanged(object sender, EventArgs e)
// 텍스트 체인지 함수 생성
{
}
private void Button_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
MessageBox.Show("포트가 열려있지 않습니다.");
return;
}
Button btn = (Button)sender;
serialPort1.Write(btn.Name.Substring(1));
}
// 컨트롤 초기화
private void button1_Click(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
if (tb != null)
{
tb.Text = string.Empty;
}
else if (ctrl is ComboBox)
{
ComboBox dd = (ComboBox)ctrl;
if (dd != null)
{
dd.Text = string.Empty;
dd.SelectedIndex = -1;
}
}
}
}
}
}
}