我在c#中找不到KeyPress事件处理程序

时间:2016-03-25 23:54:19

标签: c# textbox win-universal-app keypress

我是c#的新手。我正在尝试制作一个Windows 10应用程序,其中我有一个只接受数字和一个小数的文本框。我看到很多人在这里说使用KeyPress事件处理程序,但我没有。我只有KeyDown和KeyUp。我看到有人使用KeyDown使用以下代码发布:

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

但即便如此,我仍然得到Key.D0和Key.D9的错误“当前上下文中不存在密钥”。我完全失去了,如果有人可以提供帮助那就太棒了。

3 个答案:

答案 0 :(得分:2)

假设“Windows 10 app”是指“通用应用”,您可以在名为TextBox_KeyDown的方法中使用以下代码,该方法与TextBox的KeyDown事件相关联。

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

答案 1 :(得分:0)

假设这是一个WinForm应用程序,请参阅MSDN上的以下Control.KeyPress Event示例(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;
    }
}

希望这可能会有所帮助。

答案 2 :(得分:0)

您可以使用自定义代码手动生成此事件。我希望你明白这一点。

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