C# 按钮发送命令SerialPort1_DataReceived(EventArgs e)发送和接收响应,与不需要的响应产生冲突

C# 按钮发送命令SerialPort1_DataReceived(EventArgs e)发送和接收响应,与不需要的响应产生冲突,c#,serial-port,read-write,C#,Serial Port,Read Write,//如何创建开关盒或定义按钮值不同 阅读和显示。 有些按钮使用DataReceived事件,而其他按钮则不需要它,但会为那些需要在DataReceived事件处理程序中重新退出的按钮(如我的LoggedTabtn_Click)创建冲突 其他按钮需要ReadExisted进入button_click方法,而不是使用DataReceived事件(如my GLPBtn_click) 请说明如何修复此冲突谢谢为了正确执行此操作,您确实需要在DataReceived事件中使用状态机和委托(回调),以根据您

//如何创建开关盒或定义按钮值不同 阅读和显示。 有些按钮使用DataReceived事件,而其他按钮则不需要它,但会为那些需要在DataReceived事件处理程序中重新退出的按钮(如我的LoggedTabtn_Click)创建冲突 其他按钮需要ReadExisted进入button_click方法,而不是使用DataReceived事件(如my GLPBtn_click)


请说明如何修复此冲突谢谢

为了正确执行此操作,您确实需要在DataReceived事件中使用状态机和委托(回调),以根据您所处的状态运行正确的函数。在您的情况下,按下gui上的按钮可能会使其进入状态。我在这里写了一篇很好的文章:

嗨,巴达克,谢谢你的回答。我开始重新组织代码,使enum成为stateForButtons,并将commads按钮指向switch案例中的特定调用方法。如果您有关于如何停止GLPBtn_中的while循环的建议,请单击,我将不胜感激。如果它找到了结尾,\r它应该会完成,但它会继续。这就是为什么我的应用程序crashesHi@JimB,后台工作程序有一个
CancelAsync()
函数,当设置它时,它会告诉后台工作程序取消。在while循环中,您需要检查
是否(backgroundWorker1.CancellationPending)中断
将退出while循环。希望这有帮助。谢谢你,Baddak,我为我的DataReceived事件实现了Enum ButtonState,它工作得非常好。谢谢你,伙计。
//Button need DataRecieved  event handler
private void LoggedDataBtn_Click(object sender, EventArgs e)
{
    //When LoggDataBtn is pressed it Send the command LogToShow to  device
    string LoggedDataTOshow = "?R\r\n";
    string commForMeter = string.Format(LoggedDataTOshow);

    try
    {
        if (serialPortForApp.IsOpen)
        {
            Thread.Sleep(2000);
            serialPortForApp.Write(LoggedDataTOshow);
        }
    }
    catch (Exception)
    {
        ShowDataInScreenTxtb.Text = "TimeOUT Exception: Error for requested command";
    }
}

//button does not need DataRecieved handler to display but create conflict 
//for those that need it
private void GLPBtn_Click(object sender, EventArgs e)
{
    //send command to instrument
    string GLPCommand = "?G\r\n";
    string GLPToShow = String.Format(GLPCommand);

    try
    {
        if (serialPortForApp.IsOpen)
        {
            Thread.Sleep(2000);
            //write command to port
            serialPortForApp.Write(GLPToShow);
        }
    }
    catch
    {
        //MessageBox error if data reading is not posible
        ShowDataInScreenTxtb.Text = "TimeOUT Exception";
    }

    while (glpShowInMainForm.DataToSetandGet != "ENDS\r")
    {
        serialPortForApp.Write("\r");
        DataToSetandGet = serialPortForApp.ReadExisting();
        ShowDataInScreenTxtb.AppendText(DataToSetandGet.Replace("\r", "\r\n"));
    }
}


//event handler
private void SerialPortInApp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        // SerialPort1_DataReceived handles to recieve data from device connected to Port
        Thread.Sleep(500);
        DataToSetandGet = serialPortForApp.ReadExisting();
        // Invokes the delegate on the UI thread, and sends the data that was received to the invoked method.  
        // ---- The "SerialPortInApp_DataReceived" method will be executed on the UI thread which allows populating of the textbox.  
        if (this.InvokeRequired)
        {
            Invoke(new MethodInvoker(delegate { 
                ShowDataInScreenTxtb.AppendText(DataToSetandGet.Replace("\r", "\r\n")); 
            }));
        }

        //The requested command is responded by the invoke method sending back the answer requested to display into the Textbox( DisplayDataTxB)
        ShowDataInScreenTxtb.AppendText(DataToSetandGet.Replace("\r", "\r\n"));

        //////display message(DataReadingStatusLbl) everytime data is retreiving from through the port 
        //   DataReadingStatusLbl.Text = "Retrieving Data from TPS Instrument -->>";
    }
    catch (Exception)
    {
        ShowDataInScreenTxtb.Text = "TimeOUT Exception: Error Port ";
    }
}

private void OpenPortBtn_Click(object sender, EventArgs e)
{
    //Connect Port Button allows to connect the current device base on Port and Raud settings
    try
    {
        if (PortIndexCbx.Text == "" || BaudRateIndexCbx.Text == "")
        {
            ShowDataInScreenTxtb.Text = "Set Up your Port Settings";                    
            //Error message to user to set up port connection if empty selection
        }
        else    
        {
            //Get Serial Port index settings to display for users 
            serialPortForApp.PortName = PortIndexCbx.Text;                       


            serialPortForApp.BaudRate = Convert.ToInt32(BaudRateIndexCbx.Text);      
            serialPortForApp.DataBits = 8;                                    
            serialPortForApp.Parity = Parity.None;                            
            serialPortForApp.StopBits = StopBits.One;                         
            serialPortForApp.Handshake = Handshake.XOnXOff;                   

            //Open serial Port to allow communication between PC and device 
            //DataReceived Implemented to read from Port sending and recieving the 
            buttons command requested
            //To receive data, we will need to create an EventHandler for the 
            // "SerialDataReceivedEventHandler"

            //I delete this and GLPBtn_Click responds and work without it, but I need 
            //both buttons to work because LoggedDataBtn_Click need this event to 
            //display responds

            serialPortForApp.DataReceived += new 
            SerialDataReceivedEventHandler(SerialPortInApp_DataReceived);

            serialPortForApp.ReadTimeout = 500;
            serialPortForApp.WriteTimeout = 500;

            //serialPortForApp.RtsEnable = true;
            //serialPortForApp.DtrEnable = true;

            //Once Serial port and baud rate setting are set, 
            //connection is ready to use 
            //Open serial port for communication between device and PC
            serialPortForApp.Open();

            //Connect and close connection buttons Behaviour
            progressBarPortAccess.Value = 100;                   
            OpenPortBtn.Enabled = false;                   
            ClosePortBtn.Enabled = true;                   
            ShowDataInScreenTxtb.Enabled = true;
            ShowDataInScreenTxtb.Text = "";

            DataReadingStatusLbl.Text = "Port is Connected";
        }
    }
    catch (UnauthorizedAccessException)
    {
        ShowDataInScreenTxtb.Text = "Unauthorized Port Access";
    }
}