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;//我加的,包含串口相關的
using System.Text.RegularExpressions;//我加的
namespace WindowsFormsApplication1
{
public partial class PCZigbeeLed : Form
{
private SerialPort comm = new SerialPort();//我加的,新建一個串口變量
private bool closing = false;//是否正在關閉串口,執行Application.DoEvents,并阻止再次invoke
private bool Listening = false;//是否沒有執行完invoke相關操作
public PCZigbeeLed()//自動生成的函數
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
Array.Sort(ports);
comboPortName.Items.AddRange(ports);
comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;
//初始化SerialPort對象
comm.NewLine = "/r/n";
comm.RtsEnable = true;//根據實際情況吧。
//comm.DataReceived += comm_DataReceived;
}
private void comboPortName_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void buttonOpenClosecom_Click(object sender, EventArgs e)
{
//根據當前串口對象,來判斷操作
if (comm.IsOpen)
{
closing = true;
while (Listening) Application.DoEvents();
//打開時點擊,則關閉串口
comm.Close();
//this.timer1.Stop();
closing = false;
}
else
{
//關閉時點擊,則設置好端口,波特率后打開
comm.PortName = comboPortName.Text;
comm.BaudRate = 9600;
try
{
comm.Open();
}
catch (Exception ex)
{
//捕獲到異常信息,創建一個新的comm對象,之前的不能用了。
comm = new SerialPort();
//現實異常信息給客戶。
MessageBox.Show(ex.Message);
}
}
//設置按鈕的狀態
buttonOpenClosecom.Text = comm.IsOpen ? "關閉串口" : "打開串口";
}
private void buttonOpenLight_Click(object sender, EventArgs e)
{
byte[] SendBuf = new byte[2];
SendBuf[0] = 0x31;
SendBuf[1] = 0x31;
comm.Write(SendBuf, 0, 2);
System.Threading.Thread.Sleep(100);
}
private void buttonCloseLight_Click(object sender, EventArgs e)
{
byte[] SendBuf = new byte[2];
SendBuf[0] = 0x31;
SendBuf[1] = 0x30;
comm.Write(SendBuf, 0, 2);
System.Threading.Thread.Sleep(100);
}
}
}