如何在C#中实现仅允许输入0000到FFFF的文本框?
实现仅允许输入0000到FFFF范围值的文本框解决方案
0000到FFFF是4位十六进制值,需要同时实现三类限制:
- 仅允许输入十六进制合法字符(0-9、A-F/a-f)
- 输入长度最多4位
- 最终输入值在0000到FFFF的数值范围内
实现步骤
- 限制输入字符与长度:通过
KeyPress事件过滤非法字符,同时限制文本框内容长度不超过4位 - 验证数值范围:通过
Validating事件将输入文本转换为十六进制数值,检查是否在0(0x0000)到65535(0xFFFF)之间
完整代码示例
public partial class TextBox_Numbers_Characters : Form { public TextBox_Numbers_Characters() { InitializeComponent(); // 可选:设置文本框默认值为0000 TXTB_HEX_RANGE.Text = "0000"; } // 原仅允许字母的文本框事件(保留) private void TXTB_ONLY_CHAR_KeyPress(object sender, KeyPressEventArgs e) { if(!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar)) { e.Handled = true; } } // 原仅允许数字的文本框事件(保留) private void TXTB_ONLY_NUMBER_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } } // 限制输入0000-FFFF的十六进制文本框KeyPress事件 private void TXTB_HEX_RANGE_KeyPress(object sender, KeyPressEventArgs e) { TextBox txtBox = sender as TextBox; // 允许退格、回车等控制键 if (char.IsControl(e.KeyChar)) return; // 仅允许十六进制字符(0-9、A-F、a-f) bool isHexChar = char.IsDigit(e.KeyChar) || (e.KeyChar >= 'A' && e.KeyChar <= 'F') || (e.KeyChar >= 'a' && e.KeyChar <= 'f'); if (!isHexChar) { e.Handled = true; return; } // 限制输入长度不超过4位 if (txtBox.Text.Length >= 4) { e.Handled = true; } } // 验证输入值是否在0000-FFFF范围内 private void TXTB_HEX_RANGE_Validating(object sender, CancelEventArgs e) { TextBox txtBox = sender as TextBox; // 可选:自动补前导零至4位 if (txtBox.Text.Length < 4) { txtBox.Text = txtBox.Text.PadLeft(4, '0'); } // 尝试转换为十六进制整数 if (!int.TryParse(txtBox.Text, System.Globalization.NumberStyles.HexNumber, null, out int hexValue)) { MessageBox.Show("请输入有效的4位十六进制值"); e.Cancel = true; return; } // 检查数值范围 if (hexValue < 0 || hexValue > 0xFFFF) { MessageBox.Show("输入值必须在0000到FFFF之间"); e.Cancel = true; } } }
注意事项
- 需在设计器中给目标文本框绑定
TXTB_HEX_RANGE_KeyPress和TXTB_HEX_RANGE_Validating两个事件 - 如果需要统一显示大写字母,可在
TextChanged事件中添加txtBox.Text = txtBox.Text.ToUpper();,同时补充txtBox.SelectionStart = txtBox.Text.Length;避免光标跳回开头
内容的提问来源于stack exchange,提问作者Johnny
相关产品推荐
相关产品推荐

