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

发布于 2024-09-08 04:14:09 字数 1278 浏览 5 评论 0原文

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

当用户按下数字键时,单元格进入编辑模式并允许用户覆盖该值。如果密钥不是数字,则不会发生任何事情...

这工作得很好...问题是我发现它的代码很难看... 我似乎无法找到一种简洁的方法来处理单个条件下的所有数字键,因此我制作了一个 switch 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...]

当然,它可以工作,但是有是一个更好、更短的方法,对吗?

我使用 Google 所能找到的就是将 e.KeyCode 转换为字符,但是当使用数字键时,它甚至会给出数字值的字母......

谢谢。

I am currently handling the KeyDown event of a DataGridView control.
One of the columns is filled by calculated values and I want the user to be able to override the cell value if they want.

When the user presses a numeric key, the cell goes into EditMode and allows the user to override the value. If the key is not numeric, nothing happens...

That is working pretty well... the problem is that I find the code for it ugly...
I can't seem to find a neat way to handle all the numeric keys in a single condition, so I've made a switch case construct to deal with all the possible numeric keys, like this:

                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...]

Sure, it works, but there has to be a better and shorter way, right?

All I could find using Google is converting e.KeyCode to a char, but when using numeric keys, it goes gives letters even for the numeric values...

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

花海 2024-09-15 04:14:09

尝试

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

Try

if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
    (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
    e.KeyCode == Keys.Decimal)
{
    // Edit mode
}
温柔戏命师 2024-09-15 04:14:09

如果您使用 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");
    }
}

If you use the KeyPress event, the event signature has a KeyPressEventArgs with a KeyChar member that gives you the character for the numberpad keys. You can do a TryParse on that to figure out if its a number or not.

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    int i;
    if (int.TryParse(e.KeyChar.ToString(), out i))
    {
        MessageBox.Show("Number");
    }
}
紫南 2024-09-15 04:14:09

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) 这是我收集的有用函数之一。
您可以在此处找到它< /a>.

Sorcerer86pt's solution was the simplest, however, when a user presses a control key, like backspace, then it breaks. To solve that problem, you can use the following snippet:

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
}

If you're using WPF, you might find that a TextBox doesn't have a KeyPressed event. To fix this, I used the following code.

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;
    }
}

You may notice the weird function call WPFUtils.Interop.Keyboard.GetCharFromKey(e.Key) this is one of the useful functions I've collected.
You can find it here.

吹泡泡o 2024-09-15 04:14:09

为什么要使用键码,当你可以使用它时:

void Control_KeyPress(object sender, KeyPressEventArgs e)
    {

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

它更干净,即使微软决定更改所有枚举 vlue,它仍然可以工作

Why use keycodes, when you can use this:

void Control_KeyPress(object sender, KeyPressEventArgs e)
    {

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

It's cleaner and even if microsoft decides to change all enums vlue, it still would work

一个人练习一个人 2024-09-15 04:14:09

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)

On the msdn help page they use this code in their example:

// 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)
魂牵梦绕锁你心扉 2024-09-15 04:14:09

更精简一点的版本:

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

A bit more condensed version:

    private void KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !Char.IsDigit(e.KeyChar); // only allow a user to enter numbers
    }
尬尬 2024-09-15 04:14:09

只需从按键中获取最后一个字符,如果按下数字,该字符将是数字。
此方法适用于 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;
}

Just get the last char from the Key that will be number if a number was pressed.
This method works with KeyDown events not needing any other conditions.

Just call this static method and pass in the Key to check

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;
}
玩心态 2024-09-15 04:14:09
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");
}
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");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文