c# - 串行监视器、DataReceived 处理程序误解 C#、WPF

标签 c# wpf serial-port serial-communication

我正在为我的 WPF 应用程序开发串行监视器,使用 C# 编程。 我在管理 DataReceived 事件时遇到了麻烦,因为我想要一个实时监视器,例如 HyperTerminal 或 TeraTerm(我没有使用它们,因为我希望我的终端成为以太网通信工具的一部分,我已经使用 winPcap 开发了它) .

我必须从我的微 Controller 读取一些数据,将其显示在文本框上(它只打印一个菜单和可用命令列表),当它完成加载序列时,我想与它交互,没什么特别的,只是发送“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 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.

您可以使用Dispatcher.BeginInvokeDispatcher.Invoke 方法 编码回主线程

例子

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

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

关于c# - 串行监视器、DataReceived 处理程序误解 C#、WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50619833/

相关文章:

c# - "Failed to initialize database."

c# - 使用 PrintDocument 时出错

c# - 在 ListView 中强制调整 GridView 列的大小

c++ - 在 Windows 中使用 VMIN 和 VTIME

c# - 从 56k 调制解调器创建拨号音

c# - zlib from C++ to C#(How to convert byte[] to stream and stream to byte[])

wpf - 如何将颜色设置为窗口的高亮颜色?

c# - 应用程序在执行 Application_Startup() 后立即终止

android - 如何处理android手机中的串口?

c# - Asp.net 菜单导航事件类属性