笔者最近需要上位机与下位机进行数据交互,在广泛参考大佬的资料后,较为完善地使用Textbox控件进行数据输入的功能。感兴趣的可以了解一下
笔者最近需要上位机与下位机进行数据交互,在广泛参考大佬的资料后,较为完善地使用Textbox控件进行数据输入的功能。
程序段主要功能:实现输入数据并转换成byte数组再通过串口发送至下位机。
读取TextBox控件中数据并发送
private void Botton_Float_Click(object sender, EventArgs e)
{
if (button1.Text == "关闭串口")
{
if(TextBox_Tem_Cal.Text != String .Empty) //判断数据输入框是否为空
{
HexMath CRC = new HexMath();
Byte[] buffer = new Byte[6];
float tem_cal_float = float.Parse(TextBox_Tem_Cal.Text);
Byte[] float_byte_array = new Byte[4];
float_byte_array = FloatToBytes(tem_cal_float);
buffer[0] = float_byte_array[0];
buffer[1] = float_byte_array[1];
buffer[2] = float_byte_array[2];
buffer[3 ] = float_byte_array[3];
CRC.CalculateCrc16(buffer, out buffer[5], out buffer[4]);
serialPort1.Write(buffer, 0, 6);
}
else
{
MessageBox.Show("校准数据不能为空");
}
}
else
{
MessageBox.Show("串口未打开");
}
}
限制TextBox控件输入数据
private void TextBox_Tem_Cal_KeyPress(object sender, KeyPressEventArgs e)//在TextBox中按下按键时触发事件,保证只能输入数字
{
//判断按键是不是要输入的类型。
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
e.Handled = true;
//小数点的处理。
if ((int)e.KeyChar == 46) //小数点
{
if (TextBox_Tem_Cal.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(TextBox_Tem_Cal.Text, out oldf);
b2 = float.TryParse(TextBox_Tem_Cal.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
Float 与 byte数组 互转
private static byte[] FloatToBytes(float data)
{
unsafe
{
byte* pdata = (byte*)&data;
byte[] byteArray = new byte[sizeof(float)];
for (int i = 0; i < sizeof(float); ++i)
byteArray[i] = *pdata++;
return byteArray;
}
}
private static float BytesToFloat(byte[] data)
{
unsafe
{
float a = 0.0F;
byte i;
byte[] x = data;
void* pf;
fixed (byte* px = x)
{
pf = &a;
for (i = 0; i < data.Length; i++)
{
*((byte*)pf + i) = *(px + i);
}
}
return a;
}
}
程序参考:
TextBox输入限制
C# byte与float转换
到此这篇关于C#使用TextBox作数据输入方法的文章就介绍到这了,更多相关C# TextBox数据输入内容请搜索得得之家以前的文章希望大家以后多多支持得得之家!
织梦狗教程
本文标题为:C#使用TextBox作数据输入方法


基础教程推荐
猜你喜欢
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中的Linq to JSON操作详解 2023-06-08
- C# 解析XML和反序列化的示例 2023-04-14
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- Unity shader实现高斯模糊效果 2023-01-16
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- Unity 如何获取鼠标停留位置下的物体 2023-04-10