简体   繁体   English

如何将通过串口发送的数据输出到textBox上? C#Visual Studio

[英]How to output data sent through serial port onto a textBox? C# Visual Studio

I'm currently working on a C# application and where I read Serial Data send through the USB port, where this data is to be shown on a textbox then eventually into a database. 我目前正在使用C#应用程序,并且在其中读取通过USB端口发送的串行数据,该数据将在文本框中显示,然后最终存储到数据库中。 The code I have right now has it refresh to read serial data coming in every 2 seconds, but I cannot get the data onto the textBox. 我现在拥有的代码可以刷新以读取每2秒传入的串行数据,但是我无法将数据获取到textBox上。 I'm fairly new to C# development so I am unsure as to what the best way to output my data onto a textbox or how to fix my problem in the first place. 我对C#开发还很陌生,所以我不确定将数据输出到文本框的最佳方法是什么,或者首先如何解决问题。 My code is below. 我的代码如下。

public partial class Form1 : Form
{
    SerialPort mySerialPort = new SerialPort("COM3");
    OleDbConnection connection = new OleDbConnection();
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        if (mySerialPort.IsOpen == false)
        {
            mySerialPort.Open();
        }
    }

    public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        //gets data values from serial port
        SerialPort sp = (SerialPort)sender;
        string data = sp.ReadExisting();
        string time = GetTimestamp(DateTime.Now);

        int indata;
        long timeStamp;

        //parses strings to integers
        indata = Int32.Parse(data);
        timeStamp = Int64.Parse(time);


        //writes to console
        Console.WriteLine(indata);
        Console.WriteLine(timeStamp);

        //writes to text box
        textBox1.Text = data;

        Thread.Sleep(2000);
    }

    private void button3_Click(object sender, EventArgs e)
    {
        mySerialPort.Close();
    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    public static string GetTimestamp(DateTime value)
    {
        return value.ToString("yyyyMMddHHmmss");
    }

    private void label1_Click_1(object sender, EventArgs e)
    {

    }
}

The event DataReceived is handled with the method DataReceivedHandler on a different thread than the control textBox1 is created. 使用方法DataReceivedHandler在与创建控件textBox1不同的线程上处理DataReceived事件。 So when running your program you should have get a System.InvalidOperationException . 因此,在运行程序时,您应该获得System.InvalidOperationException Which states exactly what I just described. 哪一个正是我刚才所描述的。

To get out of this dilemma you can use the Control.BeginInvoke method which would: 为了摆脱这种困境,您可以使用Control.BeginInvoke方法,该方法将:

Execute the specified delegate asynchronously on the thread that the control's underlying handle was created on. 在创建控件的基础句柄的线程上异步执行指定的委托。

Basically it would drag the piece of code down to the thread that cretated the control. 基本上,它将代码段拖到创建控件的线程中。 In this case the main thread. 在这种情况下,主线程。 This is how you would use it: 这是您将如何使用它:

//writes to text box
textBox1.BeginInvoke(new Action(() => { textBox1.Text = data; }));

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM