1. 程式人生 > 實用技巧 >C#SerialPort串列埠的簡單使用

C#SerialPort串列埠的簡單使用

注:只要掃碼槍裝置都連線成功這段程式碼才可以使用

如果不使用SerialPort控制元件可以這樣寫 最後獲取掃碼的結果放在textbox控制元件上有掃碼槍的可以試一下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 串列埠Dome { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //宣告一個串列埠 public static SerialPort _serialPort; public void setPort(string portName, int baudRate) { //例項化一下串列埠
_serialPort = new SerialPort(); this.RegisterSerialPort(portName, baudRate); if (_serialPort.IsOpen == false) { _serialPort.Open(); }
        //不用太關注這個我也不是很懂,只要知道他是個回撥函式就可以 _serialPort.DataReceived
+= new
SerialDataReceivedEventHandler(_serialPort_DataReceived); } /// <summary> /// 註冊串列埠 /// </summary> /// <param name="portName"></param> /// <param name="baudRate"></param> public void RegisterSerialPort(string portName, int baudRate) { // 串列埠名 _serialPort.PortName = portName; // 波特率 _serialPort.BaudRate = baudRate; // 資料位 _serialPort.DataBits = 8; // 停止位 _serialPort.StopBits = StopBits.One; // 無奇偶校驗位 _serialPort.Parity = Parity.None; } private void _serialPort_DataReceived(object senderd, SerialDataReceivedEventArgs e) { //等待100ms 防止讀取不全的情況 Thread.Sleep(100); byte[] m_recvBytes = new byte[_serialPort.BytesToRead]; //獲取接受緩衝區的位元組數 定義緩衝區的大小 int result = _serialPort.Read(m_recvBytes, 0, m_recvBytes.Length);//從串列埠讀取資料 返回讀取的位元組數 if (result <= 0) { return; } //將位元組轉換成字串 //string strResult = Encoding.ASCII.GetString(m_recvBytes); string strResult = Encoding.ASCII.GetString(m_recvBytes, 0, m_recvBytes.Length); //string strResult = Encoding.UTF8..GetString(); _serialPort.DiscardInBuffer(); this.Invoke((EventHandler)(delegate { txtCK.Text = strResult; })); } private void Form1_Load(object sender, EventArgs e) {
        //引數1:串列埠(埠)號名稱 引數2:波特率 setPort(
"COM14", 9600); } } }

下面這個是使用SerialPort控制元件寫的 省略了註冊串列埠的那個方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 串列埠Dome
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        public static SerialPort serialPort = new SerialPort();
        public void setPort()
        {
            if (serialPort.IsOpen==false)
            {
                serialPort.Open();
            }
            serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
        }

        private  void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //防止讀取不全的情況 等待100ms
            Thread.Sleep(100);
            byte[] m_recvBytes = new byte[serialPort.BytesToRead];//獲取緩衝區的的位元組數
            int reslut = serialPort.Read(m_recvBytes, 0, m_recvBytes.Length);
            if (reslut <= 0)
            {
                return;
            }
            string strResult = Encoding.ASCII.GetString(m_recvBytes, 0, m_recvBytes.Length);//轉換成字串格式的

            serialPort.DiscardInBuffer();

            this.Invoke((EventHandler)(delegate
            {
                TxtCode.Text = strResult;
            }));


        }
        private void Form2_Load(object sender, EventArgs e)
        {
            var str = BarCode.PortName;
            int num = BarCode.BaudRate;
       setPort() MessageBox.Show(
"Name:" + str + " " + "波特率" + num); } } }

後期有更好的理解和寫法在補充上去