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; namespace _20151004_7SegClock { delegate void MyDelegate(string text); public partial class Form1 : Form { SerialPort port = new SerialPort(); int selectTime = 0; //0:時刻表示 1:日付表示 public Form1() { InitializeComponent(); } //アプリ起動時処理 private void Form1_Load(object sender, EventArgs e) { //使用可能なCOMポートを取得し、コンボボックスへ表示 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { comboBox1.Items.Add( port ); } comboBox1.SelectedIndex = 0; //COMポートの初期値は先頭のCOMポート comboBox2.SelectedIndex = 5; //ボーレートの初期値は9600bps } //接続処理 private void button1_Click(object sender, EventArgs e) { if( port.IsOpen == true) //どれかのポートがすでに接続されているなら、メッセージを表示して終了 { textBox1.AppendText("ポートはすでに開かれています\n"); } else { //シリアルポートの各パラメータを設定 port.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived); port.PortName = comboBox1.SelectedItem as String; port.BaudRate = int.Parse(comboBox2.SelectedItem as String); port.Parity = Parity.None; port.StopBits = StopBits.One; port.DataBits = 8; port.Handshake = Handshake.None; port.RtsEnable = true; port.DtrEnable = true; try { //エラーがなければ、シリアルポートを接続、テキストを表示、タイマー動作開始 port.Open(); textBox1.AppendText( port.PortName + " is Opened\n" ); timer1.Enabled = true; } catch { textBox1.AppendText("ポートを開けませんでした\n"); } } } //シリアル受信処理 private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { int a = port.ReadByte(); if (a == 65) //文字"A"を受信したら日付と時刻を切り替え selectTime = ~selectTime; Invoke((MethodInvoker)delegate { if (selectTime == 0) textBox1.AppendText("時刻を表示\n"); else textBox1.AppendText("日付を表示\n"); }); } //切断処理 private void button2_Click(object sender, EventArgs e) { //シリアルポートを切断、テキストを表示、タイマー動作停止 port.Close(); textBox1.AppendText(port.PortName + " is Closed\n"); timer1.Enabled = false; } //アプリ終了時処理 private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (port.IsOpen == true) //ポートが接続されたままなら、切断処理を行う { MessageBox.Show("ポート切断処理を行ってから終了します"); port.Close(); textBox1.AppendText(port.PortName + " is Closed\n"); timer1.Enabled = false; } } //タイマー Tick動作 private void timer1_Tick(object sender, EventArgs e) { if (selectTime == 0) // port.Write(DateTime.Now.ToString("HHmm")); //"時時分分"の形式で、時刻をシリアル送信 port.Write(DateTime.Now.ToString("mmss")); else port.Write(DateTime.Now.ToString("MMdd")); } } }