首页 > 解决方案 > 仅允许 TextBox 上的特定键

问题描述

我有个问题。我发现的例子是在“KeyPress”上,它们不再在 WPF 上工作

你能告诉我,如何只允许在 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();
        }
    }

标签: c#wpfkeydown

解决方案


您可以使用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");
}

推荐阅读