Mac Air本身沒有serial port可以使用,而剛好最近在玩Arduino開發版,
剛好可以用 C# 來跟我的 Arduino 通訊
不過這邊先簡單介紹怎麼取得電腦上所有的 serial port,
順便複習一下combobox 和 listbox
首先這邊先建立Windows Form Application
介面就簡單如圖所示:
// Created by vince
// Copyright (c) 2013年 vince. All rights reserved.
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; //要使用serial port需要引用它
namespace c_sharp_searchSerialPort
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string [] myPorts = SerialPort.GetPortNames(); //取得所有port的名字的方法
comboBox1.DataSource = myPorts; //直接取得所有port的名字
listBox1.DataSource = myPorts;
foreach (string port in myPorts) //使用迴圈方式取得所有port的名字
{
comboBox2.Items.Add(port); //一個一個增加
listBox2.Items.Add(port);
}
}
}
}
結果如下,可以發現直接指定所有port給combobox1(左邊),它會有預設的port跑出來,
而用迴圈添加的port給combobox2(右邊),它預設是空白,
直接指定所有port給listbobox1(左邊),它會預設選取 port 的名稱


沒有留言:
張貼留言