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.Tasks;
using System.Windows.Forms;
namespace SerialPort
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
cmdClose.Enabled = false;
foreach (String s in System.IO.Ports.SerialPort.GetPortNames())
{
txtPort.Items.Add(s);
}
}
public System.IO.Ports.SerialPort sport;
public void serialport_connect(String port, int baudrate , Parity parity, int databits, StopBits stopbits)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
sport = new System.IO.Ports.SerialPort(
port, baudrate, parity, databits, stopbits);
try
{
sport.Open();
cmdClose.Enabled = true;
cmdConnect.Enabled = false;
txtReceive.AppendText("[" + dtn + "] " + "Connected\n");
sport.DataReceived += new SerialDataReceivedEventHandler(sport_DataReceived);
}
catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
}
private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
txtReceive.AppendText("["+dtn+"] "+"Received: "+sport.ReadExisting()+"\n");
}
private void cmdConnect_Click(object sender, EventArgs e)
{
String port = txtPort.Text;
int baudrate = Convert.ToInt32(cmbbaudrate.Text);
Parity parity = (Parity)Enum.Parse(typeof(Parity), cmbparity.Text);
int databits = Convert.ToInt32(cmbdatabits.Text);
StopBits stopbits = (StopBits)Enum.Parse(typeof(StopBits), cmbstopbits.Text);
serialport_connect(port, baudrate, parity, databits, stopbits);
}
private void button1_Click(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
String data = txtDatatoSend.Text;
sport.Write(data);
txtReceive.AppendText("[" + dtn + "] " + "Sent: " + data + "\n");
}
private void cmdClose_Click_1(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
if (sport.IsOpen)
{
sport.Close();
cmdClose.Enabled = false;
cmdConnect.Enabled = true;
txtReceive.AppendText("[" + dtn + "] " + "Disconnected\n");
}
}
}
}
大家好,当我尝试将波特率从9600设置为115200时,我遇到了抛出InvalidOperationException的问题。
知道为什么会这样吗?提前谢谢。
答案 0 :(得分:1)
这里发生的是你从非UI线程获得串口回调,并且在回调中你正在尝试更改UI组件。
你不被允许这样做,你会得到你所看到的例外。
最佳解决方案取决于您使用的.Net版本,但无论您使用何种版本,都可以使用Control.BeginInvoke()
来解决它。
我提供的链接上有一些示例代码。
请注意,它没有设置导致问题的波特率。这是sport_DataReceived()
中的代码,它尝试更新UI组件(您可以从发布的第二个图像中看到)。
您可以按如下方式更改该功能:
private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.BeginInvoke(new Action(() =>
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
txtReceive.AppendText("[" + dtn + "] " + "Received: " + sport.ReadExisting() + "\n");
}));
}
这样做会导致在UI线程上调用上面Action
的代码。