[英]Serial monitor, DataReceived handler misunderstanding C#, WPF
我正在為WPF中的應用程序開發串行監視器,並使用C#進行編程。 我在管理DataReceived事件時遇到了麻煩,因為我想要一個例如HyperTerminal或TeraTerm的實時監視器(我不使用它們是因為我希望我的終端成為以太網通信工具的一部分,直到我已經使用winPcap開發過) 。
我必須從微控制器讀取一些數據,將其顯示在textBox上(它只打印菜單和可用命令列表),完成加載順序后,我想與之進行交互,沒什么特別的,只需發送一個“ flash-“命令對板的fpga進行編程。
當我嘗試使用接收到的數據更新textbox.text時,我的應用程序異常。 我嘗試在任何地方搜索,但是盡管有很多示例,但我沒有發現可以正確解釋代碼的內容。
這是代碼,在此先感謝
namespace WpfApplication1 {
/// <summary>
/// Interaction logic for SerialMonitor.xaml
/// </summary>
public partial class SerialMonitor : Window {
//VARIABLES
public SerialPort comPort = new SerialPort();
public SerialMonitor() {
//initialization
InitializeComponent();
scanPorts();
}
private void scanPorts() {
textBoxIndata.Clear();
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports) {
comboBoxPorts.Items.Add(port);
}
}
private void openComBtn_Click(object sender , RoutedEventArgs e) {
comPort.Parity = Parity.None;
comPort.DataBits = 8;
comPort.ReadTimeout = 500;
comPort.StopBits = StopBits.One;
if (comboBoxPorts.SelectedItem != null && comboBoxPorts.SelectedItem != null) {
comPort.PortName = comboBoxPorts.SelectedItem.ToString();
comPort.BaudRate = Convert.ToInt32(comboBoxBaud.Text);
try {
//Open port and add the event handler on datareceived
comPort.Open();
comPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
if (comPort.IsOpen) {
label1.Content = "COM PORT OPEN";
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
}
//function to update the textBox, didn't manage to get it working
private void updateUI (string s) {
}
//CLOSE AND EXIT BUTTONS
private void closeComBtn_Click(object sender , RoutedEventArgs e) {
if (comPort.IsOpen) {
comPort.Close();
label1.Content = "COM PORT CLOSED";
}
}
private void exitBtn_Click(object sender , RoutedEventArgs e) {
if (comPort.IsOpen) {
comPort.Close();
}
this.Close();
}
}
}
我現在遇到的問題是,當我使用SerialPort.Write(string cmd)發送命令時,我無法讀回答案...
編輯:修復了所有問題,如果有人對這樣的工具編程感興趣,我將發布代碼:)
DataReceived
事件在另一個/輔助線程上返回,這意味着您將必須重新編組回UI線程才能更新TextBox
從SerialPort對象接收數據時,在輔助線程上引發DataReceived事件。 由於此事件是在輔助線程而非主線程上引發的,因此嘗試修改主線程中的某些元素(例如UI元素)可能會引發線程異常。 如果需要修改主窗體或控件中的元素,請使用Invoke將更改請求回發,這將在適當的線程上完成工作。
您可以使用Dispatcher.BeginInvoke
或Dispatcher.Invoke Method
將其編組回主線程
〔實施例
Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
要么
someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
我現在遇到的問題是,當我使用SerialPort.Write(string cmd)發送命令時,我無法讀回答案...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.