我有一个serialport dataRecived事件,里面有2个方法。 LogFile是记录数据,drawSetpoint正在绘制图形。
public void serialPort1_DataRecived (object sender, SerialDataReceivedEventArgs e)
{
DateTime time = DateTime.Now;
string Rdata = serialPort1.ReadLine();
LogFile(Rdata, (int)numericSetpoint.Value);
drawSetpoint(time,numericSetpoint.Value.ToString());
}
两个方法都接受来自numericUpDown控件的第二个参数,该控件看起来像这个
public void numericSetpoint_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (serialPort1.IsOpen)
{
int setpoint = (int)numericSetpoint.Value;
//send to serial port .....
}
当我输入数据时,问题是我的数据已恢复事件读取数字中的两种方法。例如,如果我输入150,LogFile将显示1,15,150,绘图功能将开始绘制1,15,150。我想两个函数在按下回车键后从numericSetpoint控件获取值,所以我得到整个值。我怎么能这样做?
答案 0 :(得分:0)
您正在使用KeyPress事件。而是考虑使用ValueChanged事件,该事件仅在按下enter或用户离开控件时触发https://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown.valuechanged%28v=vs.110%29.aspx
答案 1 :(得分:0)
听起来您的数据rx事件在您输入时触发。我会尝试在数据rx事件中填充一个缓冲区,并在您发送数据之前暂停任何记录或绘图。有很多“安全”的方法可以做到这一点,但核心逻辑如下:
byte[] buffer = new byte[MAX_BUFFER];
private volatile bool _ready = false;
private Object _lock = new Object();
public void serialPort1_DataRecived (object sender, SerialDataReceivedEventArgs e)
{
DateTime time = DateTime.Now;
// Either read as bytes or convert string to bytes, add to your buffer
// string Rdata = serialPort1.ReadLine();
lock(_lock )
{
if(_ready)
{
_ready = false;
var myData = your buffer as string
// clear buffer
LogFile(myData, (int)numericSetpoint.Value);
drawSetpoint(time,numericSetpoint.Value.ToString());
}
}
}
...
public void numericSetpoint_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (serialPort1.IsOpen)
{
int setpoint = (int)numericSetpoint.Value;
//send to serial port .....
lock(_lock ) { _ready = true; }
}
}
}