简体   繁体   中英

Read \r sent by serial port in C#?

I'm sending a text by serial port to C#. This text contains \\r and it will become a new line in HyperTerminal. Now I want to read this \\r in C#. How can I do this?

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        RxString = serialPort1.ReadLine();

        this.Invoke(new EventHandler(DisplayText));
    }

    private void DisplayText(object sender, EventArgs e)
    {
        string str = RxString;

        if(str == "\r")
        {
            MessageBox.Show("This is a new line");
        }
    }

If you are using ReadLine() it will read to the line escape, this can be \\r, \\n or \\r\\n so by using the ReadLine() command you are automatically detecting your carriage return and removing it from the read string

https://msdn.microsoft.com/en-us/library/system.io.streamreader.readline%28v=vs.110%29.aspx

if for some reason you need to preserve the carriage return then you can use the Read() command

https://msdn.microsoft.com/en-us/library/ath1fht8%28v=vs.110%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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