Gali
Gali

Reputation: 14973

How to prevent a user typing all Characters Except arrow key?

i have TextBox in my WinForm profram

How to prevent a user typing all Characters Except arrow key, Esc and Enter ?

Sorry, i forgot to write this is for Windows-mobile and in Windows-mobile there isnt

e.SuppressKeyPress = true;

thanks, and sorry for the Non-understanding

Upvotes: 0

Views: 749

Answers (3)

Richard
Richard

Reputation: 30628

The KeyDown event will do this for you.

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            // These keys will be allowed
            case Keys.Left:
            case Keys.Right:
            case Keys.Up:
            case Keys.Down:
            case Keys.Escape:
            case Keys.Enter:
                break;

            // These keys will not be allowed
            default:
                e.SuppressKeyPress = true;
                break;
        }
    }

Upvotes: 1

nan
nan

Reputation: 20316

As BoltClock wrote those characters are not printable so you cannot 'type' them. If you meant to ignore these characters and do sth else for other characters, you can do that in the KeyDown event of the textbox.

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (
            e.KeyCode == Keys.Left || 
            e.KeyCode == Keys.Right ||
            e.KeyCode == Keys.Down ||
            e.KeyCode == Keys.Up ||
            e.KeyCode == Keys.Enter || 
            e.KeyCode == Keys.Escape
            )
        {
            e.SuppressKeyPress = true;
            return;
        }
        //do sth...
    }

Upvotes: 0

Axarydax
Axarydax

Reputation: 16623

You can handle event TextBox.KeyDown.

There filter keys you do not want to pass through to the TextBox - check if KeyEventArgs.KeyCode is your code)

Then set KeyEventArgs.Handled and KeyEventArgs.SuppressKeyPress to true.

Upvotes: 0

Related Questions