简体   繁体   中英

Serial monitor, DataReceived handler misunderstanding C#, WPF

I'm developing a serial monitor for my application in WPF, programming in C#. I have trouble managing the DataReceived event, because i want a real time monitor like HyperTerminal or TeraTerm for example (I'm not using them because I want my terminal to be a part of an ethernet communication tool, wich I already developed using winPcap).

I have to read some data from my microcontroller, display it on the textBox (It just prints a menu and the list of commands available) and when it finishes the loading sequence I would like to interact with it, nothing special, just send a "flash-" command to program the fpga of the board.

My application goes in exception when I try to update the textbox.text with the data received. I tried to search everywhere but despite a lot of examples, I didn't catch something which is explaining the code properly.

Here is the code, thanks in advance

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();
    }
}

}

I got now the problem that when i send my command using SerialPort.Write(string cmd) , I can't read back the answer...

EDIT: Fixed everything, I will post the code if anyone is interested in programming a tool like this one :)

DataReceived event returns on another/secondary thread, which means you will have to marshal back to the UI thread to update your TextBox

SerialPort.DataReceived Event

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.

You can use Dispatcher.BeginInvoke or Dispatcher.Invoke Method to marshal back to the main thread

Exmaple

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

or

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

我现在遇到的问题是,当我使用SerialPort.Write(string cmd)发送命令时,我无法读回答案...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM