좋아요! 그러면 **WinForms GUI**로 COM 포트 통신 프로그램을 만드는 예제를 단계별로 만들어 드릴게요.
기본 기능은 다음과 같습니다:
* 연결 가능한 COM 포트 목록 표시 → 선택 후 연결/해제
* 송신용 텍스트박스 → 전송 버튼
* 수신 로그 표시 → 실시간 업데이트
---
## 1️⃣ WinForms GUI 기본 구성
1. **Form 디자인**
* ComboBox → `comboBoxPorts` (포트 선택)
* Button → `buttonConnect` (연결/해제)
* TextBox → `textBoxSend` (보낼 데이터 입력)
* Button → `buttonSend` (데이터 전송)
* TextBox → `textBoxLog` (수신 로그, `Multiline = true`, `ScrollBars = Vertical`)
---
## 2️⃣ 코드 예제
```csharp
using System;
using Systehttp://m.IO.Ports;
using Systehttp://m.Windows.Forms;
namespace SerialPortGUI
{
public partial class Form1 : Form
{
SerialPort serialPort = new SerialPort();
public Form1()
{
InitializeComponent();
LoadCOMPorts();
serialPort.DataReceived += SerialPort_DataReceived;
}
private void LoadCOMPorts()
{
comboBoxPorts.Items.Clear();
string[] ports = SerialPort.GetPortNames();
comboBoxPorts.Items.AddRange(ports);
if (ports.Length > 0)
comboBoxPorts.SelectedIndex = 0;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
if (!serialPort.IsOpen)
{
serialPort.PortName = comboBoxPorts.Text;
serialPort.BaudRate = 9600;
serialPort.Parity = Parity.None;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
serialPort.Handshake = Handshake.None;
serialPort.Open();
buttonConnect.Text = "Disconnect";
Log("포트 열림: " + serialPort.PortName);
}
else
{
serialPort.Close();
buttonConnect.Text = "Connect";
Log("포트 닫힘");
}
}
catch (Exception ex)
{
MessageBox.Show("오류: " + ex.Message);
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
serialPort.WriteLine(textBoxSend.Text);
Log("송신: " + textBoxSend.Text);
textBoxSend.Clear();
}
else
{
MessageBox.Show("포트가 열려 있지 않습니다.");
}
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = serialPort.ReadExisting();
this.Invoke(new Action(() => Log("수신: " + data)));
}
private void Log(string message)
{
textBoxLog.AppendText(DateTime.Now.ToString("HH:mm:ss") + " - " + message + Environment.NewLine);
}
}
}
```
---
## 3️⃣ 기능 설명
1. **COM 포트 자동 로딩**
* `SerialPort.GetPortNames()`로 현재 사용 가능한 포트 목록 가져오기
2. **연결/해제**
* `serialPort.Open()` / `serialPort.Close()`
* 버튼 텍스트 변경으로 상태 표시
3. **데이터 송신**
* `WriteLine` 사용 → 수신 장치에서 줄바꿈 단위로 받음
4. **데이터 수신**
* `DataReceived` 이벤트 → UI 업데이트는 `Invoke` 필요
5. **로그 표시**
* `textBoxLog.AppendText`로 시간과 함께 송수신 표시
---
💡 **팁**
* BaudRate, Parity 등 통신 설정은 실제 장치에 맞춰 변경
* 실시간 수신 데이터가 많으면 TextBox 대신 **ListBox**나 **RichTextBox** 사용 추천
---
원하면 제가 이 예제를 **실시간 그래프 + 수신 로그 GUI**까지 확장해서, 장치 상태까지 한눈에 볼 수 있게 만들어 드릴 수도 있어요.
혹시 그쪽까지도 만들어 드릴까요?