C#使用TextBox作數(shù)據(jù)輸入方法
筆者最近需要上位機與下位機進行數(shù)據(jù)交互,在廣泛參考大佬的資料后,較為完善地使用Textbox控件進行數(shù)據(jù)輸入的功能。
程序段主要功能:實現(xiàn)輸入數(shù)據(jù)并轉換成byte數(shù)組再通過串口發(fā)送至下位機。
讀取TextBox控件中數(shù)據(jù)并發(fā)送
private void Botton_Float_Click(object sender, EventArgs e) { if (button1.Text == "關閉串口") { if(TextBox_Tem_Cal.Text != String .Empty) //判斷數(shù)據(jù)輸入框是否為空 { 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("校準數(shù)據(jù)不能為空"); } } else { MessageBox.Show("串口未打開"); } }
限制TextBox控件輸入數(shù)據(jù)
private void TextBox_Tem_Cal_KeyPress(object sender, KeyPressEventArgs e)//在TextBox中按下按鍵時觸發(fā)事件,保證只能輸入數(shù)字 { //判斷按鍵是不是要輸入的類型。 if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46) e.Handled = true; //小數(shù)點的處理。 if ((int)e.KeyChar == 46) //小數(shù)點 { if (TextBox_Tem_Cal.Text.Length <= 0) e.Handled = true; //小數(shù)點不能在第一位 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數(shù)組 互轉
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; } }
程序參考:
到此這篇關于C#使用TextBox作數(shù)據(jù)輸入方法的文章就介紹到這了,更多相關C# TextBox數(shù)據(jù)輸入內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#動態(tài)創(chuàng)建button按鈕的方法實例詳解
這篇文章主要介紹了C#動態(tài)創(chuàng)建button按鈕的方法實例詳解的相關資料,需要的朋友可以參考下2017-06-06C#使用DateAndTime.DateDiff實現(xiàn)計算年齡
這篇文章主要為大家詳細介紹了C#如何使用DateAndTime.DateDiff實現(xiàn)根據(jù)生日計算年齡,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2024-01-01