页面效果
代码(这是一个winform程序,一共也没有几个控件,相信其他的代码能够通过页面效果推断出来,如果不熟的话我会传一个完整的工程)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp12
{
public partial class Form1 : Form
{
SynchronizationContext m_SyncContext = null;
SerialPort serialPort1;
public Form1()
{
InitializeComponent();
m_SyncContext = SynchronizationContext.Current;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
serialPort1 = new SerialPort(textBox2.Text);
serialPort1.Open();
setStr("\n启动成功");
}
catch (Exception ex) {
setStr(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
byte[] bf = new byte[1000];
serialPort1.Read(bf, 0, 1000);
String str = Encoding.ASCII.GetString(bf);
textBox1.AppendText("\n"+str);
}
private void button3_Click(object sender, EventArgs e)
{
Task t = new Task(() =>
{
while (true) {
byte[] bf = new byte[1000];
serialPort1.Read(bf, 0, 1000);
String str = Encoding.ASCII.GetString(bf);
//textBox1.AppendText("\n" + str);
m_SyncContext.Post(setStr, str);
}
});
t.Start();
}
private void setStr(Object o) {
textBox1.AppendText("\r\n"+o.ToString());
}
}
}
运行效果