串行端口接收的数据继续运行,无需单击按钮 [英] Serial Port Received data continues without button click

查看:65
本文介绍了串行端口接收的数据继续运行,无需单击按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在WPF中制作了一个GUI,可以通过RS232和...读取数据.
唯一的问题是我必须继续按
一个向我的控制器发送接收数据"命令的按钮
通过RS232,以便将数据发送回去.我想实施
这是连续/实时的,所以我不必保留
按下按钮即可与我的设备通信.我
在while循环中编写的代码只是冻结了我的程序,我已经
还尝试了一个复选框,因此如果选中该复选框,则会获取数据和
这也冻结了GUI.

只是想知道C#和wpf中是否有任何解决方案

I''ve made a GUI in WPF to read data via RS232 and.
The only problem is I have to keep pressing
a button to send a ''Receive data'' command to my controller
via RS232 so it sends the data back. I want to implement
this in continuously/real time so I don''t have to keep
pressing a button to communicate with my device. I''ve
written while loops and that just freezes my program, i''ve
also tried a checkbox so if it''s checked it gets data and
that also freezes the GUI.

Just wanted to know if there is any solution in C# and wpf

SerialPort sp;
  sp.DataReceived += new SerialDataReceivedEventHandler(receive);


 private void receive(object sender, SerialDataReceivedEventArgs e)
        {
                string data;
                data = sp.ReadExisting();
                MyLog(data);
        }
private void MyLog(string msg)
        {

                this.Dispatcher.Invoke(new DisplayTextDelegate(DisplayText), msg);
        }
        private void DisplayText(string text)
        {
             TextBox2.AppendText(text);
        }

        private void SendButton_Click(object sender, RoutedEventArgs e)
        {

             sp.Write(TextBox1.Text+ "\r\n");

        }

推荐答案

这可能会有更多帮助:

This may be a little more help:

public MainWindow()
{
  InitializeComponent();

  var bw = new BackgroundWorker();
  bw.DoWork += new DoWorkEventHandler(bw_DoWork);
  bw.WorkerSupportsCancellation = true;
  bw.WorkerReportsProgress = true;
  bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
  bw.RunWorkerAsync();

}

void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  //Update UI here
  var newText = e.UserState;
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{
  var bw = (BackgroundWorker) sender;
  while (!bw.CancellationPending)
  {
    //Do RS-232 stuff here
    var newText = "Put new information here";
    bw.ReportProgress(1, newText);
  }
}


使用System.ComponentModel.BackgroundWorker并将您的代码放入其DoWork事件中.
这样,RS232读取将在后台发生,并且不会阻止GUI.
然后,您的按钮(或复选框)应启动/停止此BackgroungWorker.
有许多示例说明如何正确使用BackgroundWorker以及如何基于其处理更新GUI.
Use System.ComponentModel.BackgroundWorker and put your code in it''s DoWork event.
That way RS232 reading will happen in background and will not block GUI.
Your button (or checkbox) should then start/stop this BackgroungWorker.
There are many examples how to use BackgroundWorker properly and how to update GUI based on it''s processing.


这篇关于串行端口接收的数据继续运行,无需单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆