当有人拨打我的固定电话时,我正在使用 SerialPort 获取来电显示。我已经使用 PuTTy 软件对其进行了测试,它运行良好。
然而,我的 C# 代码抛出了一个 InvalidOperation 异常,并指出:跨线程操作无效:控件lblCallerIDTitle
从创建它的线程以外的线程访问。当我尝试这样做时会发生此错误:lblCallerIDTitle.Text = ReadData;
我怎样才能解决这个问题?下面是我的代码:
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.IO.Ports;
namespace CallerID
{
public partial class CallerID : Form
{
public CallerID()
{
InitializeComponent();
port.Open();
WatchModem();
SetModem();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
WatchModem();
}
private SerialPort port = new SerialPort("COM3");
string CallName;
string CallNumber;
string ReadData;
private void SetModem()
{
port.WriteLine("AT+VCID=1\n");
port.RtsEnable = true;
}
private void WatchModem()
{
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReadData = port.ReadExisting();
//Add code to split up/decode the incoming data
lblCallerIDTitle.Text = ReadData;
Console.WriteLine(ReadData);
}
private void CallerID_Load(object sender, EventArgs e)
{
}
}
}
我想要一个标签来显示传入的数据。谢谢