Created
September 3, 2013 20:42
-
-
Save thinkAmi/6429288 to your computer and use it in GitHub Desktop.
WindowsFormでのシリアルポート通信のサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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