Search code examples
c#textboxwin-universal-appkeypress

I can not find KeyPress event handler in c#


I am new to c#. I am trying to make a windows 10 app in which I have a text box that only accepts numbers and one decimal. I have seen many people here saying to use KeyPress event handler but I do not have that. I only have KeyDown and KeyUp. I saw someone post using the following code with KeyDown:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key < Key.D0 || e.Key > Key.D9)
    {
        e.Handled = true;
    }
}

but even for this I get the error "Key does not exist in the current context" for Key.D0 and Key.D9. I am at a complete loss, if someone can help that would be great.


Solution

  • Assuming by "Windows 10 app" you mean a "Universal App", you can use the following code in a method named TextBox_KeyDown that you associate with the KeyDown event of your TextBox.

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if(e.Key < Windows.System.VirtualKey.Number0 || e.Key >= Windows.System.VirtualKey.Number9)
        {
            e.Handled = true;
        }
    }