簡體   English   中英

C#Winforms,從numericupdown存儲值

[英]C# winforms, storing value from numericupdown

我有一個帶有2個方法的serialport dataRecived事件。 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,而draw函數將開始繪制1,15,150。 我希望這兩個函數都可以在按下回車鍵之后從numericSetpoint控件中獲取值,以便獲得整個值。 我該怎么辦?

您正在使用KeyPress事件。 而是考慮使用ValueChanged事件,該事件僅在按下Enter鍵或用戶離開控件時才會觸發, 網址為https://msdn.microsoft.com/zh-cn/library/system.windows.forms.numericupdown.valuechanged%28v=vs.110 %29.aspx

聽起來您的數據rx事件在您鍵入時正在觸發。 我會嘗試在您的data 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; }               
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM