我有一个小问题。制作十六进制掩码后,我无法使用 Ctrl + C / V 进行复制/粘贴。如果我右键单击文本框,我可以粘贴。但我希望能够按 Ctrl + V 。
如果我删除了十六进制掩码, Ctrl + C / V 工作正常。
以下是一些代码:
private void maskedTextBox1(Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// this will allow a-f, A-F, 0-9, ","
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "^[0-9a-fA-F,V,C,'\b']+$"))
{
e.Handled = true;
}
// if keychar == 13this ill allow <ENTER>
if (e.KeyChar == (char)13)
{
button1_Click(sender, e);
}
// I thought I could fix it with the lines below but it doesnt work
/* if (e.KeyChar == (char)22)
{
// <CTRL + C>
e.Handled = true;
}
if (e.KeyChar == (char)03)
{
// is <CTRL + V>
e.Handled = true;
}*/
//MessageBox.Show(((int)e.KeyChar).ToString());
}
有人可以给我一些提示吗?
答案 0 :(得分:1)
您需要使用KeyDown事件处理程序捕获这些击键,而不是KeyPressed。 KeyPressed仅用于键入键。
MaskedTextBox在这里并不理想,您也可以使用常规TextBox。使用Validating事件格式化数字并检查范围。例如:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
bool ok = e.KeyChar == 8; // Backspace
if ("0123456789ABCDEF".Contains(char.ToUpper(e.KeyChar))) ok = true;
if (!ok) e.Handled = true;
}
private void textBox1_Validating(object sender, CancelEventArgs e) {
int value;
if (textBox1.Text.Length > 0) {
if (!int.TryParse(this.textBox1.Text, System.Globalization.NumberStyles.HexNumber, null, out value)) {
this.textBox1.SelectAll();
e.Cancel = true;
}
else {
textBox1.Text = value.ToString("X8");
}
}
}
答案 1 :(得分:0)
MaskedTextBox
可能会阻止 Ctrl + V 调用(否则您可以轻松绕过掩码)。就个人而言,我不会使用蒙面文本框,而是单独验证输入,并在输入出现问题时提醒用户。 MaskedTextBox
在一般使用中有缺点,因为它不是用户习惯的普通组件,用户更习惯被告知输入错误。
答案 2 :(得分:0)
你有:
if (e.KeyChar == (char)03)
{
// is <CTRL + V>
e.Handled = true;
}*/
根据Cisco
Ctrl + V 的值为22
,因此您应该:
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "^[0-9a-fA-F,V,C,'\b']+$") && e.KeyChar != 22)
{
e.Handled = true;
}