问题描述
我已经在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");
}
推荐答案
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);
}
}
这篇关于串行端口接收的数据继续运行,无需单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!