简体   繁体   中英

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 ie

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??

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM