C#使用TextBox作数据输入方法

2022-10-26 12:39:45

笔者最近需要上位机与下位机进行数据交互,在广泛参考大佬的资料后,较为完善地使用Textbox控件进行数据输入的功能。
程序段主要功能:实现输入数据并转换成byte数组再通过串口发送至下位机。

读取TextBox控件中数据并发送

privatevoidBotton_Float_Click(object sender, EventArgs e){if(button1.Text=="关闭串口"){if(TextBox_Tem_Cal.Text!= String.Empty)//判断数据输入框是否为空{
             HexMath CRC=newHexMath();
             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控件输入数据

privatevoidTextBox_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数组 互转

privatestatic 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;}}privatestaticfloatBytesToFloat(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转换

  • 作者:怪都督
  • 原文链接:https://blog.csdn.net/weixin_44625313/article/details/114329916
    更新时间:2022-10-26 12:39:45