仅允许TextBox

时间:2018-05-19 16:56:33

标签: c# wpf keydown

我有一个问题。我找到的例子是" KeyPress"他们不再在WPF上工作了

你能告诉我,如何只允许来自keybord的指定键在WPF文本框上写入?我知道keyUp和Down函数,但是如何通过类型定义我想要的字母呢?

我认为这将更容易,如果我将发布我的代码,我告诉你我想做什么。这里有什么改变?

private void textBox_KeyDown(object sender, KeyEventArgs e)
    {
        //something here to only allow "A" key to be pressed and displeyed into textbox
        if (e.Key == Key.A)
        {                
            stoper.Start();
        }
    }

private void textBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.A)
        {
            //here i stop the stopwatch to count time of pressing the key
            stoper.Stop();
            string aS = stoper.ElapsedMilliseconds.ToString();
            int aI = Convert.ToInt32(aS);
            stoper.Reset();
        }
    }

2 个答案:

答案 0 :(得分:1)

您可以使用PreviewKeyDown并使用e.Key过滤掉您需要的内容。

或者,在代码的任何位置,您可以使用Keyboard类:

if (Keyboard.IsKeyDown(Key.E)) { /* your code */ }

<强>更新

要禁止密钥,您需要将事件设置为已处理:

if (e.Key == Key.E)
{
    e.Handled = true;
    MessageBox.Show($"{e.Key.ToString()} is forbidden");
}

答案 1 :(得分:0)

这件事对我来说非常好(感谢@JohnyL):

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    //something here to only allow "A" key to be pressed and displeyed into textbox
    if (e.Key == Key.A)
    {                
        stoper.Start();
    }
    else
        e.Handled = true;
}

private void textBox_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.A)
    {
        //here i stop the stopwatch to count time of pressing the key
        stoper.Stop();
        string aS = stoper.ElapsedMilliseconds.ToString();
        int aI = Convert.ToInt32(aS);
        stoper.Reset();
    }
}