从Windows窗体初始化为“COM1”,事件处理程序为:
ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = ComPort.ReadExisting();
if (InputData != String.Empty)
{
this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
}
}
private void SetText(string text)
{
Response = Encoding.UTF8.GetBytes(text);
}
在表格中
private byte[] Response = null;
private int MaxAttempts = 1
private int Attempts = 0;
private bool Launch = true;
点击按钮控件后,我有:
private void btnTest_Click(object sender, EventArgs e)
{
byte[] BufferTest = new byte[1];
BufferTest[0] = 1;
System.Timers.Timer Temp = new System.Timers.Timer(2000);
Temp.Elapsed += OnTimedEvent; //See this function below
Temp.Enabled = true;
while (Response == null && Attempts < MaxAttempts)
{
if (Launch)
{
Launch = false;
ComPort.Write(BufferTest, 0, BufferTest.Length);
}
}
//Right here Response is still null despite there was bytes read at serial port
}
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
Attempts++;
Launch = true;
}
在btnTest_Click方法结束时,尽管在串行端口读取了字节,但仍然为响应,并设置响应。会发生什么是在btnTest_Click完成后调用SetText()。我期待在事件时调用SetText(),然后中断while循环,从而获得响应。
请帮忙???