How can I accept the backspace key in the keypress event?

后端 未结 8 570
长情又很酷
长情又很酷 2020-12-16 10:39

This is my code:

private void txtAdd_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!(char.IsLetter(e.KeyChar)) && !(char.IsNumber(e.KeyChar)         


        
相关标签:
8条回答
  • 2020-12-16 11:18

    The backspace key does not raised by KeyPress event. So you need to catch it in KeyDown or KeyUp events and set SuppressKeyPress property is true to prevent backspace key change your text in textbox:

    private void txtAdd_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Back)
        {
            e.SuppressKeyPress = true;
        }
    }
    
    0 讨论(0)
  • 2020-12-16 11:20

    I like to use !Char.IsControl(e.KeyChar) so that all the "control" characters like the backspace key and clipboard keyboard shortcuts are exempted.

    If you just want to check for backspace, you can probably get away with:

    if (e.KeyChar == (char)8 && ...)
    
    0 讨论(0)
  • 2020-12-16 11:26

    From the documentation:

    The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

    0 讨论(0)
  • 2020-12-16 11:27

    You have to add !(char.IsControl(e.KeyChar)) in you sentence and that's it.

    private void txtNombre_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (!(char.IsLetter(e.KeyChar)) && !(char.IsNumber(e.KeyChar)) && !(char.IsControl(e.KeyChar)) && !(char.IsWhiteSpace(e.KeyChar)))
                {
                    e.Handled = true;
                }
            }
    
    0 讨论(0)
  • 2020-12-16 11:33
    private void Keypressusername(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(char.IsLetter(e.KeyChar));
        if (char.IsControl(e.KeyChar))
        {
            e.Handled = !(char.IsControl(e.KeyChar));
        }
        if (char.IsWhiteSpace(e.KeyChar))
        {
            e.Handled = !(char.IsWhiteSpace(e.KeyChar));
        }
    }
    
    0 讨论(0)
  • 2020-12-16 11:35

    for your problem try this its work for when backspace key pressed

    e.KeyChar == ((char)Keys.Back)
    
    0 讨论(0)
提交回复
热议问题