Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - How can I accept the backspace key in the keypress event?

This is my code:

private void txtAdd_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!(char.IsLetter(e.KeyChar)) && !(char.IsNumber(e.KeyChar)) && !(char.IsWhiteSpace(e.KeyChar)))
    {
        e.Handled = true;
    }
}

It allows me to enter letters, numbers and spaces but it doesn't allow me to do backspace. Please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 && ...)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...