コード例 #1
0
ファイル: Form1.cs プロジェクト: icprog/SerialportProgramming
        void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs ee)
        {
            textBox6CallBack callback = delegate()
            {
                try
                {
                    if (serialPort.IsOpen)
                    {
                        toolStripStatusLabel1.Text = "正在接收数据。。。。";
                        int    bytes  = serialPort.BytesToRead;
                        byte[] buffer = new byte[bytes];
                        serialPort.Read(buffer, 0, bytes);
                        builder.Clear();
                        foreach (byte b in buffer)
                        {
                            builder.Append(b.ToString("X2") + " ");
                        }
                        textBox6.AppendText("接收数据:" + builder.ToString());
                        textBox6.AppendText(Environment.NewLine);
                        toolStripStatusLabel1.Text = "数据接收完成。。。。";
                    }
                    else
                    {
                        MessageBox.Show("请打开串口!!", "错误提示");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            };

            textBox6.Invoke(callback);
        }
コード例 #2
0
ファイル: Form1.cs プロジェクト: icprog/SerialportProgramming
        private void timer1_Tick_1(object sender, EventArgs e)
        {
            textBox6CallBack callback = delegate()
            {
                try
                {
                    string str      = "010400000020F1D2";
                    byte[] Sendbyte = new byte[str.Length / 2];
                    for (int i = 0, j = 0; i < str.Length; i = i + 2, j++)
                    {
                        string mysubstring = str.Substring(i, 2);
                        Sendbyte[j] = Convert.ToByte(mysubstring, 16);
                    }
                    serialPort.Write(Sendbyte, 0, Sendbyte.Length);

                    textBox6.AppendText("发送信息[电机:" + DateTime.Now + "]" + "01 04 00 00 00 20 F1 D2\r\n");
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "提示信息");
                }
            };

            textBox6.Invoke(callback);
        }