C#: TextBox文本框输入十六进制数值的处理

十六进制数值的输入控制(KeyPress事件):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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         }
复制代码

 

posted @   linux_farmer  阅读(4264)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示