繁体   English   中英

KeyDown事件 - 如何轻松知道按下的键是否为数字?

[英]KeyDown event - how to easily know if the key pressed is numeric?

我目前正在处理DataGridView控件的KeyDown事件。 其中一列由计算值填充,我希望用户能够在需要时覆盖单元格值。

当用户按下数字键时,单元格进入EditMode并允许用户覆盖该值。 如果密钥不是数字,则没有任何反应......

这工作得很好......问题是我找到了丑陋的代码...我似乎无法找到一个简单的方法来处理单一条件下的所有数字键,所以我做了一个开关case构造来处理所有可能的数字键,如下所示:

                switch (e.KeyCode)
                {
                    case Keys.D0:
                    case Keys.D1:
                    case Keys.D2:
                    case Keys.D3:
                    case Keys.D4:
                    case Keys.D5:
                    case Keys.D6:
                    case Keys.D7:
                    case Keys.D8:
                    case Keys.D9:
                    case Keys.Decimal:
                    case Keys.NumPad0:
                    case Keys.NumPad1:
                    case Keys.NumPad2:
                    case Keys.NumPad3:
                    case Keys.NumPad4:
                    case Keys.NumPad5:
                    case Keys.NumPad6:
                    case Keys.NumPad7:
                    case Keys.NumPad8:
                    case Keys.NumPad9:

                         [code to make the cell go to editMode, etc...]

当然,它有效,但必须有更好更短的方式,对吧?

我使用谷歌找到的只是将e.KeyCode转换为字符,但是当使用数字键时,它甚至会为数字值提供字母...

谢谢。

尝试

if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
    (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
    e.KeyCode == Keys.Decimal)
{
    // Edit mode
}

如果您使用KeyPress事件,则事件签名具有KeyPressEventArgs其中包含KeyChar成员,该成员为您提供数字键盘的字符。 您可以在其上执行TryParse以确定它是否为数字。

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    int i;
    if (int.TryParse(e.KeyChar.ToString(), out i))
    {
        MessageBox.Show("Number");
    }
}

为什么使用密钥代码,当你可以使用它:

void Control_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (Char.IsDigit(e.KeyChar))
        {
            //do something
        }
        else
        {
            //do something else
        }
    }

它更干净,即使微软决定改变所有的enums vlue,它仍然会工作

Sorcerer86pt的解决方案是最简单的,但是,当用户按下控制键(如退格键)时,它会中断。 要解决该问题,您可以使用以下代码段:

void KeyPress(object sender, KeyPressEventArgs e)
{    
    if(!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
    {
        //The char is not a number or a control key
        //Handle the event so the key press is accepted
        e.Handled = true;
        //Get out of there - make it safe to add stuff after the if statement
        return;
    }
    //e.Handled remains false so the keypress is not accepted
}

如果您正在使用WPF,您可能会发现TextBox没有KeyPressed事件。 为了解决这个问题,我使用了以下代码。

void ValidateKeyPress(object sender, KeyEventArgs e)
{
    char keyPressed = WPFUtils.Interop.Keyboard.GetCharFromKey(e.Key);
    if (!Char.IsNumber(keyPressed) && !Char.IsControl(keyPressed))
    {
        //As above
        e.Handled = true;
        return;
    }
}

您可能会注意到奇怪的函数调用WPFUtils.Interop.Keyboard.GetCharFromKey(e.Key)这是我收集的有用函数之一。 你可以在这里找到它。

如果按下了数字,只需从Key获取最后一个字符,该字符将是数字。 此方法适用于不需要任何其他条件的KeyDown事件。

只需调用此静态方法并传入Key进行检查

public static bool IsNumber(Keys key)
{
  string num = key.ToString().Substring(key.ToString().Length - 1);
  Int64 i64;
  if (Int64.TryParse(num, out i64))
  {
    return true;               
  }
  return false;
}

更简洁的版本:

    private void KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !Char.IsDigit(e.KeyChar); // only allow a user to enter numbers
    }

msdn帮助页面上,他们在他们的示例中使用此代码:

// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)

...

// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
void dataGridView1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Used this to find they key values.
    //label1.Text += e.KeyValue;

    // Check if key is numeric value.
    if((e.KeyValue >= 48 && e.KeyValue <= 57) || (e.KeyValue >= 97 && e.KeyValue <= 105))
        System.Console.WriteLine("Pressed key is numeric");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM