在c#中连接时捕获串行欢迎消息

时间:2016-12-07 13:24:11

标签: c# .net

我正在尝试编写一个与控制器通信的程序。当连接成功建立时,控制器应该发送“欢迎”消息,事实上,当我使用通信软件连接时,它会发送。但是,使用下面的.NET代码,我从未看到欢迎消息。除此之外,它有效。我该如何捕获此消息。它似乎是在建立连接的那一刻发送的。

同样,我能够在连接后与控制器进行良好的通信,但我似乎无法获得在连接打开时发送的欢迎消息。

using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public delegate void AddDataDelegate(String myString);
        public AddDataDelegate myDelegate;
        SerialPort sp;
        public Form1()
        {
            InitializeComponent();
        }

        public void AddDataMethod(String myString)
        {
            richTextBox1.AppendText(myString);
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.ScrollToCaret();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {                
                sp = new SerialPort(comboBox1.SelectedItem.ToString(),Int32.Parse(comboBox2.SelectedItem.ToString()));
                sp.DataReceived += SerialPort_OnDataReceived;
                sp.Close();
                sp.Open();
                richTextBox1.AppendText("open\n");
                button2.Enabled = true;
                button3.Enabled = true;
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(ex.Message);
            }
        }
        void SerialPort_OnDataReceived(object sender,SerialDataReceivedEventArgs args)
        {
            SerialPort sp = sender as SerialPort;            
            string s = sp.ReadExisting();
            richTextBox1.Invoke(this.myDelegate, new Object[] { s });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sp.WriteLine(textBox1.Text);
            textBox1.Text = "";
        }    

        private void button3_Click(object sender, EventArgs e)
        {
            sp.DiscardOutBuffer();
            sp.DiscardInBuffer();
            sp.Close();
            richTextBox1.AppendText("\nclosed\n");

        }
        private void Form1_Load_1(object sender, EventArgs e)
        {
            this.myDelegate = new AddDataDelegate(AddDataMethod);
            string[] Ports = SerialPort.GetPortNames();
            comboBox2.SelectedIndex = comboBox2.Items.Count - 1;
            Array.Sort(Ports, (a, b) => string.Compare(a.Substring(3).PadLeft(3, '0'), b.Substring(3).PadLeft(3, '0')));
            foreach (string port in Ports)
            {
                comboBox1.Items.Add(port);
            }
            comboBox1.SelectedIndex = 0;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。连接和尝试从端口提取数据之间需要稍微延迟。