日期:2014-05-18 浏览次数:20858 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO.Ports; namespace com测试 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { } Mutex m_Mutex = null;//锁 private void Form1_Load(object sender, EventArgs e) { serialPort1 = new SerialPort("com1", 2400, Parity.Even, 7, StopBits.One); m_Mutex = new Mutex(); flag = false; } delegate void setTextCallback(string msg); bool flag; SerialPort serialPort1; private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (flag==true) { return; } m_Mutex.WaitOne();//这个地方加一个互斥 if (serialPort1.IsOpen) { setTextCallback d = new setTextCallback(addText); string temp = serialPort1.ReadTo("49").ToString(); this.BeginInvoke(d, new object[] { temp }); } m_Mutex.ReleaseMutex(); } void addText(string msg) { richTextBox1.AppendText(msg); } private void btnOpen_Click(object sender, EventArgs e) { this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived); serialPort1.Open(); this.btnOpen.Enabled = false; this.btnClose.Enabled = true; this.flag = false; } private void btnClose_Click(object sender, EventArgs e) { m_Mutex.WaitOne(); { this.serialPort1.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);//先关掉对应的事件 } serialPort1.Close();//然后关掉程序 flag = true; m_Mutex.ReleaseMutex(); this.btnOpen.Enabled = true; this.btnClose.Enabled = false; } } } }