pramod choudhari
pramod choudhari

Reputation: 313

How to detect multiple keys entered in c# keydown event of textbox?

I want to design a numeric textbox in silverlight.

I have added keydown event of TextBox to handle the keypress.

Inside event I validate the key entered in the textbox.

event as follows

  private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (!this.Validate(sender,e))
            e.Handled = true;
    }

function Validate as follows

  private bool Validate(object sender, KeyEventArgs e)
    {

        if (e.Key == Key.Enter) //accept enter and tab
        {
            return true;
        }
        if (e.Key == Key.Tab)
        {
            return true;
        }

        if (e.Key < Key.D0 || e.Key > Key.D9) //accept number on alphnumeric key
            if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9) //accept number fomr NumPad
                if (e.Key != Key.Back) //accept backspace
                    return false;

        return true;
    }

I am not able to detect shift and Key.D0 to Key.D1 i.e.

SHIFT + 1 which returns "!"

SHIFT + 3 returns "#" like wise any other special keys.

I dont want user to enter special character in to textbox.

How do i handle this keys event??

Upvotes: 1

Views: 4544

Answers (3)

JOG
JOG

Reputation: 5640

In Silverlight, I don't think there are any Modifiers in the KeyEventArgs class but instead in Keyboard:

    public void KeyDown(KeyEventArgs e)
    {
        if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.D0)
        {
            ControlZero();
        }
    }

Upvotes: 6

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

textBox2.Text = string.Empty;
textBox2.Text = e.Modifiers.ToString() + " + " + e.KeyCode.ToString();

Upvotes: 0

Bradley Uffner
Bradley Uffner

Reputation: 17001

e should have a property on it that will tell you if Shift, Control or Alt are pressed. e.Modifiers can also give you additional information about which additional modifier keys have been pressed.

To cancel the character you can set e.Handled to True, which will cause the control to ignore the keypress.

Upvotes: 0

Related Questions