프로그래밍/C,C++,C#

[C# .NET] 시리얼포트 리스트 생성(feat. ComboBox)

Beginner:) 2022. 7. 4.
320x100

[장치 관리자]에 가면 현재 내 컴퓨터에 연결되어 있는 시리얼 포트(Serial Port)들이 나열되어있다.

 

C# Winform에서 콤보박스로 표현해보자. (매우 간단)

 

 

먼저 연결되어 있는 Serial들을 불러오는 코드는 아래와 같다.

string[] serial_list = SerialPort.GetPortNames();

string 배열로 값들이 불러와진다.

 

그럼 이쁘게 콤보박스에 담아본다.

 

Serial port는 항상 바뀔 수 있는 데이터들이기에 리스트를 불러들이는 때는 콤보 박스를 드롭 다운할 때이다.

 

Form 생성자 또는 초기화 함수 등에서 드롭다운 이벤트를 추가한다.

(콤보박스의 이름은 cb_serial_port이며 이벤트 함수는 cb_serial_portDropDownEvent이다)

 

public Form1(){
	InitializeComponent();
	this.cb_serial_port.DropDown += new System.EventHandler(cb_serial_portDropDownEvent);
}

 

private void cb_serial_portDropDownEvent(object sender, EventArgs e)
{
    this.cb_serial_port.Items.Clear();
    string[] serial_list = SerialPort.GetPortNames();

    foreach (string name in serial_list)
    {
        this.cb_serial_port.Items.Add(name);
    }
}

 

콤보박스를콤보 박스를 드롭다운(클릭)할 때마다 콤보 박스를 초기화한 다음 현재 연결되어 있는 Serial을 불러오면 된다.

 

 

반응형

댓글