我使用SerialPort來獲取來電顯示,當有人打我的座機時。我已經使用PuTTy軟件進行了測試,並且工作正常。使用SerialPort的來電顯示C#
但是,我的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)
{
}
}
}
我想要一個標籤來顯示傳入的數據。謝謝
可能重複[ThreadControl.Invoke](http://stackoverflow.com/questions/1423446/thread-control-invoke) –
http://www.yoda.arachsys.com/csharp/threads/winforms。 shtml - 可能這就是你要找的。 –