public partial class MainForm : Form
{
private static int lineReadCounter = 0;
public string DataToSetandGet = String.Empty;
private void StatusBtn_Click(object sender, EventArgs e)
{
string StatusInfoToshow = "?S\r";
string commForMeter = string.Format(StatusInfoToshow);
try
{
if (statusofMeter.serialPortForApp.IsOpen)
{
statusofMeter.serialPortForApp.Write(commForMeter);
}
}
catch (Exception)
{
statusofMeter.ShowDataInScreenTxtb.Text = "TimeOUT Exception";
}
}
public void SerialPortInApp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DataToSetandGet = serialPortForApp.ReadExisting();
string pattern = @"^[a-zA-Z0-9\s\-?\*?\.?\/\:\\r]{1,}$";
Match rgxs = Regex.Match(DataToSetandGet, pattern);
if (rgxs.Success && DataToSetandGet.Length > 50 &&
DataToSetandGet.IndexOf("\r") == DataToSetandGet.Length - 1)
{
lineReadCounter++;
this.BeginInvoke((Action)delegate ()
{
Textbox1.AppendText(lineReadCounter.ToString() +
DataToSetandGet.Substring(4).Replace("\n", " ").Replace("\r", "\r\n"));
});
}
}
private void CountReadings()
{
//Count Readings
string[] lines =
Regex.Split(textbox1.Text.Trim(), "\r\n");//Trim avoid white spaces
lineReadCounter = lines.Length;
label1.Text = "No. Readings: " + lineReadCounter.ToString();
}
}
如果我按下按钮StatusBtn_Click
,它将发送命令并显示
lineReadCounter +阅读
lineReadCounter
从1
开始,第一次按下该按钮。但从lineReadCounter
开始2
再按一次第二次和下一次。
每次按下按钮如何将lineReadCounter
重置为zero
或1
?
答案 0 :(得分:0)
放入
lineReadCounter = 0;
之前
statusofMeter.serialPortForApp.Write(commForMeter);
因此您的btnClick事件将如下所示:
private void StatusBtn_Click(object sender, EventArgs e)
{
string StatusInfoToshow = "?S\r";
string commForMeter = string.Format(StatusInfoToshow);
try
{
if (statusofMeter.serialPortForApp.IsOpen)
{
lineReadCounter = 0;
statusofMeter.serialPortForApp.Write(commForMeter);
}
}
catch (Exception)
{
statusofMeter.ShowDataInScreenTxtb.Text = "TimeOUT Exception";
}
}
我认为您订阅了SerialPort.DataReceived
事件,因此如果您调用Write()
,则会调用SerialPortInApp_DataReceived
方法。我觉得对吗?