c# - 仅允许 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();
}
}
解决方案
您可以使用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");
}
推荐阅读
- python - 如何在Python中获取包含多个单词的所有句子
- macos - macOS 上的多个网络扩展
- javascript - 无论如何我可以重构它以使用过滤器等数组函数
- statistics - 计算对数正态分布置信区间的修正 Cox 方法
- nestjs - 如何使用 Faker 库生成 ISO 3166-1 alpha-3 国家代码?
- angular - 过滤订阅数据后,需要获取初始数据
- pandas - 无法一次填充 matplotlib 动画帧
- r - 将两条 Kaplan Meier 曲线与 ggsurvplot 合并
- r - 用 ggplot2 绘制 mantel.rtest
- javascript - 如何通过 Javascript 选择图像 src