我有以下代码需要从端口读取数据然后在文本框中显示。我为此目的使用DataReceived事件处理程序,但不知道如何在文本框中显示此数据。从各种来源我了解到Invoke方法应该用于此,但不知道如何使用它。建议请...
private void Form1_Load(object sender, EventArgs e)
{
//SerialPort mySerialPort = new SerialPort("COM3");
mySerialPort.PortName = "COM3";
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
mySerialPort.Open();
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s= sp.ReadExisting();
// next i want to display the data in s in a textbox. textbox1.text=s gives a cross thread exception
}
private void button1_Click(object sender, EventArgs e)
{
mySerialPort.WriteLine("AT+CMGL=\"ALL\"");
}
答案 0 :(得分:12)
MSDN包含一个好的article,其中包含有关使用其他线程的控制方法和属性的示例。
简而言之,您需要的是一个委托方法,它使用给定的字符串设置文本框的Text
属性。然后,通过mySerialPort_DataReceived
方法从TextBox.Invoke()
处理程序中调用该委托。像这样:
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
private void Form1_Load(object sender, EventArgs e)
{
//...
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
textbox1.AppendText(myString);
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s= sp.ReadExisting();
textbox1.Invoke(this.myDelegate, new Object[] {s});
}
答案 1 :(得分:2)
试试这个(适合我):
private delegate void UpdateUiTextDelegate(string text);
private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (mySerialPort.IsOpen)
{
RxString = mySerialPort.ReadLine();
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), RxString);
}
}
private void DisplayText(string RxString)
{
myTextBox.Text = RxString;
}
答案 2 :(得分:2)
我正在创建一个GUI" Form"用于USB COM端口。这就是我如何将数据发送到窗口而不会得到一个"交叉线程"错误。
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string inData = serialPort1.ReadLine(); // ReadLine includes the + "\n"
displayToWindow(inData);
}
private void displayToWindow(string inData)
{
BeginInvoke(new EventHandler(delegate
{
richTextBox1.AppendText(inData);
richTextBox1.ScrollToCaret();
}));
}