如何在文本框上附加Rx数据?

时间:2018-12-05 20:19:38

标签: c# winforms

我试图做一个接口来监视串行端口。我正在使用可视表单。因此,我创建了一个组合框来选择PortCOM,创建一个TextBox来将数据发送到Serial Port,并创建一个TextBoxReceber来接收Serial Data。我尝试打印在TextBoxReceber中接收到的数据,但我使用的是AppendText,但没有成功。有人可以帮助我吗?

我的Form1.cs是:

namespace ConsoleESP
{
  public partial class Form1 : Form
{
    string RxString = "";
    public Form1()
    {
        InitializeComponent();
        timerCOM.Enabled = true;
        atualizaCOMs();

    }

    private void atualizaCOMs()
    {
        int i = 0;
        bool quantDif = false;

        if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
        {
            foreach (string s in SerialPort.GetPortNames())
            {
                if (comboBox1.Items[i++].Equals(s) == false)
                {
                    quantDif = true;
                }
            }
        }
        else quantDif = true;

        if (quantDif == false) return;

        comboBox1.Items.Clear();

        foreach(string s in SerialPort.GetPortNames())
        {
            comboBox1.Items.Add(s);
        }
        comboBox1.SelectedIndex = 0;
    }

    private void timerCOM_Tick(object sender, EventArgs e)
    {
        atualizaCOMs();
    }

    private void btConnect_Click(object sender, EventArgs e)
    {
        if(serialPort1.IsOpen == false)
        {
            try
            {
                serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
                serialPort1.Open();
            }
            catch
            {
                return;
            }
            if (serialPort1.IsOpen)
            {
                btConnect.Text = "Desconectar";
                comboBox1.Enabled = false;
            }
        }
        else
        {
            try
            {
                serialPort1.Close();
                comboBox1.Enabled = true;
                btConnect.Text = "Conectar";
            }
            catch
            {
                return;
            }
        }
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (serialPort1.IsOpen == true) serialPort1.Close();
    }

    private void btEnviar_Click(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen == true)
        serialPort1.Write(textBoxEnviar.Text);
    }

    private delegate void RefreshTextBox();

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        RxString = serialPort1.ReadExisting();
        this.Invoke(new EventHandler(TrataDadoRecebido));

    }

    private void TrataDadoRecebido(object sender, EventArgs e)
    {
        textBoxReceber.AppendText(RxString);

    }


  }
}

0 个答案:

没有答案