C# ~ ComPort2Keyboard 範例 [接收RS232 轉 (模擬​)鍵盤輸出]

C# ~ ComPort2Keyboard 範例 [接收RS232 轉 (模擬​)鍵盤輸出]

C# ~ ComPort2Keyboard 範例 [接收RS232 轉 (模擬)鍵盤輸出]


資料來源:

https://www.cnblogs.com/xinaixia/p/6216745.html
https://dotblogs.com.tw/jimmyyu/2009/09/21/10733


功能列表

    01.讓視窗縮小到工具列吧-NotifyIcon
    02.ComPort(RS232)監聽
    03.模擬鍵盤輸出


code:

namespace ComPort2Keyboard
{
    partial class Main
    {
        /// <summary>
        /// 設計工具所需的變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清除任何使用中的資源。
        /// </summary>
        /// <param name="disposing">如果應該處置 Managed 資源則為 true,否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form 設計工具產生的程式碼

        /// <summary>
        /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改
        /// 這個方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));
            this.button1 = new System.Windows.Forms.Button();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(247, 7);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Connect";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // comboBox1
            // 
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(12, 9);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(121, 20);
            this.comboBox1.TabIndex = 1;
            // 
            // notifyIcon1
            // 
            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
            this.notifyIcon1.Text = "ComPort2Keyboard";
            this.notifyIcon1.Visible = true;
            this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
            // 
            // Main
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(349, 35);
            this.Controls.Add(this.comboBox1);
            this.Controls.Add(this.button1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "Main";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "ComPort2Keyboard";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing);
            this.Load += new System.EventHandler(this.Main_Load);
            this.SizeChanged += new System.EventHandler(this.Main_SizeChanged);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.NotifyIcon notifyIcon1;
    }
}

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

namespace ComPort2Keyboard
{
    public partial class Main : Form
    {
        [DllImport("user32")]
        public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
        public SerialPort m_port = new SerialPort();
        public void SendKeybd(String StrData)
        {
            for (int i = 0; i < StrData.Length; i++)
            {
                String StrBuf = StrData.Substring(i, 1);
                byte[] byteArray = System.Text.Encoding.Default.GetBytes(StrBuf);
                for (int j = 0; j < byteArray.Length; j++)
                {
                    if(byteArray[j] > 59)
                    {
                        keybd_event(0x10, 0, 0, 0);//VK_SHIFT
                        keybd_event(byteArray[j], 0, 0, 0); //按下i
                        keybd_event(byteArray[j], 0, 2, 0); //按下i后松开
                        keybd_event(0x10, 0, 2, 0);//VK_SHIFT
                    }
                    else
                    {
                        keybd_event(byteArray[j], 0, 0, 0); //按下i
                        keybd_event(byteArray[j], 0, 2, 0); //按下i后松开
                    }
                }
                Thread.Sleep(20);
            }

            keybd_event(13, 0, 0, 0); //按下Enter
            keybd_event(13, 0, 2, 0); //按下Enter后松开
        }

        public bool ByteArray2String(byte[] pdata, ref String StrData, bool blnReverse = true)//陣列轉字串
        {
            StrData = "";
            bool blnResult = true;

            if (blnReverse == true)
            {
                Array.Reverse(pdata);
            }

            try
            {
                for (int i = 0; i < pdata.Length; i++)
                {
                    StrData += Convert.ToString(pdata[i], 16).PadLeft(2, '0');
                }
            }
            catch
            {
                blnResult = false;
            }
            return blnResult;
        }

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            string[] serialPorts = SerialPort.GetPortNames();
            ArrayList ALCpuSerialPorts = new ArrayList();
            for (int i = 0; i < serialPorts.Length; i++)
            {
                ALCpuSerialPorts.Add(serialPorts[i]);
            }
            comboBox1.DataSource = ALCpuSerialPorts;
        }

        public void CommDataReceived(Object sender, SerialDataReceivedEventArgs e)
        {
            //https://www.cnblogs.com/xinaixia/p/6216745.html
            try
            {
                //Comm.BytesToRead中为要读入的字节长度
                int len = m_port.BytesToRead;
                Byte[] readBuffer = new Byte[len];
                m_port.Read(readBuffer, 0, len); //将数据读入缓存
                //处理readBuffer中的数据,自定义处理过程
                String msg = "";
                ByteArray2String(readBuffer, ref msg, true);
                msg = msg.Substring(8, 8).ToUpper();
                SendKeybd(msg);
            }
            catch (Exception ex)
            {
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(!m_port.IsOpen)
            {
                m_port.PortName = comboBox1.SelectedItem.ToString();
                m_port.BaudRate = 115200;//jash.liao modified at 2020/02/12 
                m_port.DataBits = 8;
                m_port.StopBits = StopBits.One;
                m_port.Parity = Parity.None;
                m_port.ReadTimeout = 1;
                m_port.ReadTimeout = 3000; //单位毫秒
                m_port.WriteTimeout = 3000; //单位毫秒
                //串口控件成员变量,字面意思为接收字节阀值,
                //串口对象在收到这样长度的数据之后会触发事件处理函数
                //一般都设为1
                m_port.ReceivedBytesThreshold = 1;
                m_port.DataReceived += new SerialDataReceivedEventHandler(CommDataReceived); //设置数据接收事件(监听)
                m_port.Open();
                button1.Text = "Disconnect";
                this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            }
            else
            {
                button1.Text = "Connect";
                m_port.Close();
            }

        }

        private void Main_SizeChanged(object sender, EventArgs e)
        {
            //https://dotblogs.com.tw/jimmyyu/2009/09/21/10733
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            //https://dotblogs.com.tw/jimmyyu/2009/09/21/10733
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_port.IsOpen)
            {
                m_port.Close();
            }
        }
    }
}

2 thoughts on “C# ~ ComPort2Keyboard 範例 [接收RS232 轉 (模擬​)鍵盤輸出]

  1. C# Windows Forms 視窗 大小設定 控制
    縮小到工具列
    WindowState=System.Windows.Forms.FormWindowState.Minimized

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *