C#: TextBox文本框輸入十六進制數值的處理


十六進制數值的輸入控制(KeyPress事件):

        private void textBox_hex_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            //e.Handled = e.KeyChar < '0' || e.KeyChar > '9';  //允許輸入數字
            e.Handled = !((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar >= 'a' && e.KeyChar <= 'f') || (e.KeyChar >= 'A' && e.KeyChar <= 'F'));
            if (e.KeyChar == (char)8)  //允許輸入回退鍵
            {
                e.Handled = false;
            }
            if (e.KeyChar == 'x')  //允許輸入‘x’
            {
                e.Handled = false;
            }
            if (e.KeyChar == 'X')  //允許輸入'X'
            {
                e.Handled = false;
            }
        }

數值的轉換:public static int StringToHexOrDec(string strData)

 1         public static int StringToHexOrDec(string strData)
 2         {
 3             int dData = -1;
 4             try
 5             {
 6                 if ((strData.Length > 2))
 7                 {
 8                     if ((strData.Substring(0, 2).Equals("0x")) || (strData.Substring(0, 2).Equals("0X")))
 9                     {
10                         string str_sub = strData.Substring(2, strData.Length - 2);
11                         dData = int.Parse(str_sub, System.Globalization.NumberStyles.HexNumber);
12                     }
13                     else
14                     {
15                         dData = int.Parse(strData, System.Globalization.NumberStyles.Integer);
16                     }
17                 }
18                 else
19                 {
20                     dData = int.Parse(strData, System.Globalization.NumberStyles.Integer);
21                 }
22             }
23             catch (Exception)
24             {
25                 //MessageBox.Show("輸入錯誤: " + strData, "錯誤");
26             }
27             return dData;
28         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM