怎么在C#中使用TextBox作数据输入方法?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
读取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;
}
}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注天达云行业资讯频道,感谢您对天达云的支持。