---
title: "串口编程"
author: "devilhand"
date: "2010-11-02T11:09:15Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-11-02T12:08:05Z"
id: 800407
url: "https://devilhand.iteye.com/blog/800407"
---

**C#串口编程1.虚拟串口软件**

由于手上没有串口硬件，所以在网上找了一个 VSPM 虚拟串口软件 ，据说是免费的。

下载地址：http://www.skycn.com/soft/30517.html

刚开始也不知道怎么用，摸索了一下，终于成功。

安装以后工作模式选择应该为：VSPM运行在Server模式，支持Client模式设备

然后是使用设备探测器简历虚拟串口。（如果选择 建立默认的串口，软件就会自动帮你建立四个虚拟串口的）之后就是新增虚拟串口

串口选COM2，选择监听的IP地址：本机IP，Client模式的设备尝试连接此端口：8099

建立之后：选择此串口，再选择菜单栏：检查此设备连接，输入刚才新增时候选择的IP地址：本机IP，刚才选择的端口：8099

点击重新连接，这个窗口没有什么反映：但是主窗口的串口最右边一栏：最后一次操作：显示客户端已经建立TCP/IP连接

 

```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using Microsoft.VisualBasic;

namespace WindowsApplication4
{
    public partial class Form2 : Form
    {
        private SerialPort com = null;
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Byte[] bytes=MyEncode(textBox1.Text.Trim());
            com.Write(bytes, 0, bytes.Length);           
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
            foreach (string s in pc.Ports.SerialPortNames)
            { this.comboBox1.Items.Add(s); }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            Byte[] bytes = new Byte[com.ReadBufferSize];
            com.Read(bytes, 0, bytes.Length);
            listBox1.Items.Add(MyDecode(bytes));
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            MessageBox.Show(MyDecode(bytes));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (com == null)
            {
                com = new SerialPort(comboBox1.Text);
            }
            if (!com.IsOpen)
            {

                com.Open();
                button3.Enabled = false;
                button4.Enabled = true;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (com != null && com.IsOpen)
            {
                com.Close();
                button3.Enabled = true;
                button4.Enabled = false;
            }
        }

        /// <summary>
        /// 编码   
        /// </summary>
        private Byte[] MyEncode(string text)
        {
            Encoder ed = Encoding.Default.GetEncoder();
            char[] chars = text.ToCharArray();
            Byte[] bytes = new Byte[ed.GetByteCount(chars, 0, chars.Length, true)];
            ed.GetBytes(chars, 0, chars.Length, bytes, 0, true);
            //return Convert.ToBase64String(bytes);
            return bytes;
        }

        /// <summary>
        /// 解码
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private string MyDecode(Byte[] bytes)
        {
            Decoder dd = Encoding.Default.GetDecoder();
            char[] chars = new char[dd.GetCharCount(bytes, 0, bytes.Length, true)];
            dd.GetChars(bytes, 0, bytes.Length, chars, 0, true);
            StringBuilder result = new StringBuilder(1000);
            foreach (char c in chars)
            {
                result.Append(c);
            }
            return result.ToString();
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            button4.PerformClick();
        }

    }
}
```

 

 串口向设备发送信息

![](http://dl.iteye.com/upload/attachment/341457/021a2180-7bb5-32cc-accf-73ffb8f5dcc3.gif)

![](http://dl.iteye.com/upload/attachment/341460/232da321-6de2-3e18-ac41-023b4c9a1cbb.gif)  
 

串口接收设备发送的信息

![](http://dl.iteye.com/upload/attachment/341464/537cb0b7-74a7-3a6a-9db9-88a70e0d99ec.gif)

![](http://dl.iteye.com/upload/attachment/341466/e4205051-47f0-3d66-b70b-e8f04ad17659.gif)