Skip to content

Instantly share code, notes, and snippets.

@thinkAmi
Created September 3, 2013 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkAmi/6429288 to your computer and use it in GitHub Desktop.
Save thinkAmi/6429288 to your computer and use it in GitHub Desktop.
WindowsFormでのシリアルポート通信のサンプル
using System;
using System.Windows.Forms;
namespace SerialTest
{
public partial class CallForm : Form
{
public CallForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// シリアルポートからの読込開始
var dialog = new ReceiveForm();
dialog.ShowDialog();
// モーダルフォーム終了後、読込データを反映
textBox1.Text = dialog.ReadCode;
}
}
}
using System;
using System.Windows.Forms;
namespace SerialTest
{
public partial class ReceiveForm : Form
{
// シリアルポートから読み込んだデータ
public string ReadCode { get; private set; }
public ReceiveForm()
{
InitializeComponent();
}
private void ReceiveForm_Load(object sender, EventArgs e)
{
serialPort1.Open();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Close();
this.Close();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// シリアルポートより受信した際の、末尾文字列
serialPort1.NewLine = Environment.NewLine;
// 受信データの追加
var code = serialPort1.ReadLine();
// Control.Invokeメソッドで、UIスレッドへ処理を反映(タイプ量が少ない生成方式を使った)
this.Invoke(new MethodInvoker(() => ReadCode += code + Environment.NewLine));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment