C#實現掃碼槍串列埠通訊

CSF践行發表於2024-09-17

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.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class frm_SerianTest : Form
    {
        /// <summary>
        /// frm_SerianTest建構函式
        /// </summary>
        public frm_SerianTest()
        {
            InitializeComponent();//部件初始化
        }

        private SerialPort SerialPort_0 = new SerialPort();//例項化串列埠裝置
        //private Encoding Encoding_0 = Encoding.Default;//選用預設編碼模式

        /// <summary>
        /// 定時器事件:實現系統時間獲取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            //實現系統時間顯示
            Lbl_SysTime.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }

        /// <summary>
        /// 視窗載入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frm_SerianTest_Load(object sender, EventArgs e)
        {
           
            timer1.Interval = 1000;//時間間隔1000 單位:ms
            timer1.Start();//啟用間隔時間事件
            timer1.Tick += timer1_Tick;
          
            //獲取可用埠號
            string[] Ports = SerialPort.GetPortNames();
            if (Ports.Length>0)//獲取陣列長度大於0
            {
                cmb_Port.DataSource = Ports;//獲取到的埠號賦值給Cmb_Port
            }

            //波特率設定
            int[] Bauds = { 1200, 2400, 4800, 9600, 12800, 115200 };
            cmb_BaudRate.DataSource = Bauds;
            cmb_BaudRate.SelectedIndex = 3;//開機預設9600

            //校驗位設定(typeof:可以取得變數的型別,或者表示式的型別)
            cmb_ParityBit.DataSource = Enum.GetNames(typeof(Parity));//獲取Parity列舉的各名稱;

            //資料位設定
            int[] DataBits = { 5, 6, 7, 8 };
            cmb_DateBit.DataSource = DataBits;
            cmb_DateBit.SelectedIndex = 3;

            //停止位設定
            cmb_StopBit.DataSource = Enum.GetNames(typeof(StopBits));//獲取Parity列舉的各名稱;
            cmb_StopBit.SelectedIndex = 1;



        }
        /// <summary>
        /// 重新整理可用埠事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            string[] Ports = SerialPort.GetPortNames();//獲取電腦中可用的埠
            if (Ports.Length > 0)
            {
                cmb_Port.DataSource = Ports;
            }
        }

        /// <summary>
        /// 與虛擬串列埠裝置建立連線事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ConnectReader_Click(object sender, EventArgs e)
        {
            if (btn_ConnectReader.Text == "連線")
            {
                if (SerialPort_0.IsOpen)//如果已經建立連線則先斷開
                {
                    SerialPort_0.Close();
                }

                try //(*Trim()是去空格*)
                {
                    SerialPort_0.PortName = cmb_Port.Text.Trim();
                    SerialPort_0.BaudRate = Convert.ToInt32(cmb_BaudRate.Text.Trim());
                    SerialPort_0.DataBits = Convert.ToInt32(cmb_DateBit.Text.Trim());
                    SerialPort_0.Parity = (Parity)Enum.Parse(typeof(Parity), cmb_ParityBit.Text.Trim(), true);//將comboBox中的字串轉換為Parity列舉型別
                    SerialPort_0.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmb_StopBit.Text.Trim(), true);//將comboBox中的字串轉換為StopBits列舉型別
                    SerialPort_0.Encoding = Encoding.Default;//選用預設編碼方式
                    SerialPort_0.ReceivedBytesThreshold = 1;//預設快取區為1個位元組
                    SerialPort_0.DataReceived += SerialPort_0_DataReceived;
                    SerialPort_0.Open();//開啟連線

                    //MessageBox.Show("連線成功");
                    Log("連線成功!" );

                    //禁用眾多通訊引數配置選項
                    btn_Refresh.Enabled = false;
                    btn_ConnectReader.Text = "斷開";
                    cmb_Port.Enabled = false;
                    cmb_BaudRate.Enabled = false;
                    cmb_DateBit.Enabled = false;
                    cmb_StopBit.Enabled = false;
                    cmb_ParityBit.Enabled = false;
                }
                catch (Exception ex)
                {

                    //MessageBox.Show("連線失敗"+ex.Message);
                    Log("連線失敗!" + ex.Message);
                }

            }
            else if (btn_ConnectReader.Text == "斷開")
            {
                SerialPort_0.Close();
                //MessageBox.Show("斷開成功");
                Log("已斷開!");

                //啟用通訊引數配置項
                btn_Refresh.Enabled = true;
                btn_ConnectReader.Text = "連線";
                cmb_Port.Enabled = true;
                cmb_BaudRate.Enabled = true;
                cmb_DateBit.Enabled = true;
                cmb_StopBit.Enabled = true;
                cmb_ParityBit.Enabled = true;
            }




            
        }

        private void SerialPort_0_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                //因為要訪問UI資源,所以需要使用invoke方式同步ui
                this.Invoke((EventHandler)(delegate
                {
                    string result = string.Empty;
                    result = SerialPort_0.ReadExisting();
                    Log("掃碼結果:" + result);
                })
                );

            }
            catch (Exception ex)
            {
                //響鈴並顯示異常給使用者
                //System.Media.SystemSounds.Beep.Play();
                Log(ex.Message);
            }
        }
      
        //透過ListView將資訊顯示
        private void Log(string info)
        {
            Invoke(new Action(() =>
            {
                string time = DateTime.Now.ToString();
                ListViewItem Lst = new ListViewItem(time);
                Lst.SubItems.Add(info);
                listView1.Items.Insert(0, Lst);
            }));


        }

        private void btn_ManulCode_Click(object sender, EventArgs e)
        {
            if (tbox_ManulCode.Text==string.Empty)
            {
                Log("條碼資訊不能為空!");         
            }
            else
            {
                Log("手動輸入條碼結果:" + tbox_ManulCode.Text);
                tbox_ManulCode.Text = "";
            }
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {
            if (SerialPort_0.IsOpen)
            {
                if (tbox_SendData.Text != string.Empty)
                {
                    try
                    {
                        SerialPort_0.Write(tbox_SendData.Text.Trim());
                    }
                    catch (Exception ex)
                    {

                        Log("傳送失敗," + ex);
                    }
                    
                    Log("傳送內容:" + tbox_SendData.Text);
                }
                else
                {
                    Log("沒有傳送內容!");
                }

            }
            else
            {
                Log("串列埠未開啟!");
            }
        }


    }
}

相關文章