首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >只允许TextBox上的特定键

只允许TextBox上的特定键
EN

Stack Overflow用户
提问于 2018-05-19 16:56:33
回答 2查看 784关注 0票数 0

我有个问题。我在"KeyPress“上找到的例子,它们不再使用WPF。

您能告诉我,如何只允许在WPF文本框上写入keybord中指定的键?我知道keyUp和Down函数,但是如何定义我想要输入的字母呢?

如果我发布我的代码并告诉你我想做什么,我想这会更容易。这里要换什么?

代码语言:javascript
运行
复制
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();
        }
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-19 17:03:01

您可以使用PreviewKeyDown并使用e.Key筛选出所需的内容。

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

代码语言:javascript
运行
复制
if (Keyboard.IsKeyDown(Key.E)) { /* your code */ }

更新

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

代码语言:javascript
运行
复制
if (e.Key == Key.E)
{
    e.Handled = true;
    MessageBox.Show($"{e.Key.ToString()} is forbidden");
}
票数 1
EN

Stack Overflow用户

发布于 2018-05-20 15:17:08

这个东西对我来说很好(谢谢@JohnyL):

代码语言:javascript
运行
复制
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();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50427556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档