首页 > 编程技术 > csharp

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

发布时间:2021-6-1 15:01

笔者最近需要上位机与下位机进行数据交互,在广泛参考大佬的资料后,较为完善地使用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数据输入内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: