本週在一個上位機項目中需要將TextBox中的輸入轉爲十六進制發給串口助手,添加一個TextBox,一個Button,一個SerialPort後在VS2017中調試通過,以下直接貼代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SerialPort
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] SendBytes = null;
string SendData = textBox1.Text;
SendData = SendData.Replace(" ", "");
//每兩個字符組成一個字節放入
List<string> SendDataList = new List<string>();
for (int i = 0; i < SendData.Length; i = i + 2)
{
SendDataList.Add(SendData.Substring(i, 2));
}
SendBytes = new byte[SendDataList.Count];
for (int j = 0; j < SendBytes.Length; j++)
{
SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16));
}
serialPort1.Write(SendBytes, 0, SendBytes.Length);
}
}
}