简体   繁体   中英

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.

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;
    }
}

Assuming this is a WinForm app, refer to the following Control.KeyPress Event sample at MSDN (re: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx )

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the condition
    if (SOME CONDITION)
    {
        // Stop the character from being entered into the control.
        e.Handled = true;
    }
}

Hope this may help.

You can use a custom code to generate this event manually. I hope you get the idea.

    public YourFormName()
    {
        InitializeComponent();

        this.KeyPress -= YourFormName_KeyPress;
        this.KeyPress += YourFormName_KeyPress;
    }

    private void YourFormName_KeyPress(object sender, KeyPressEventArgs e)
    {
        //Check for any key you want.
        if (e.KeyChar == (char)Keys.Enter)
        {
            //do anything.
        }
    }

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