Maria Sheikh
Maria Sheikh

Reputation: 87

How to handle the form's KeyPress event?

I am making a program in which I am using this code,

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{          
    if (e.KeyChar >= 48 && e.KeyChar <= 57)
    {
        txtbox.Text = txtbox.Text + e.KeyChar.ToString();
    }
}

But I am not getting key pressed on my text box.I am unable to find the failure reason.

Upvotes: 2

Views: 80

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460018

According to this you have to set Form.KeyPreview to true, default is false. Otherwise you can't handle the form's KeyPress event.

When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events.

Upvotes: 1

Related Questions