仅允许 TextBox 上的特定键
Allow only specific keys on TextBox
我有一个问题。我发现的示例在 "KeyPress" 上,它们不再在 WPF
上工作
你能告诉我,如何只允许键盘指定的键写入WPF文本框吗?我知道 keyUp 和 Down 函数,但是如何定义我想要输入的字母?
我想这会更容易,如果我 post 我的代码并告诉你我想做什么。这里要改什么?
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 class:
if (Keyboard.IsKeyDown(Key.E)) { /* your code */ }
更新:
要禁止按键,您需要将事件设置为已处理:
if (e.Key == Key.E)
{
e.Handled = true;
MessageBox.Show($"{e.Key.ToString()} is forbidden");
}
那东西对我来说很好用(感谢@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();
}
}
我有一个问题。我发现的示例在 "KeyPress" 上,它们不再在 WPF
上工作你能告诉我,如何只允许键盘指定的键写入WPF文本框吗?我知道 keyUp 和 Down 函数,但是如何定义我想要输入的字母?
我想这会更容易,如果我 post 我的代码并告诉你我想做什么。这里要改什么?
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 class:
if (Keyboard.IsKeyDown(Key.E)) { /* your code */ }
更新:
要禁止按键,您需要将事件设置为已处理:
if (e.Key == Key.E)
{
e.Handled = true;
MessageBox.Show($"{e.Key.ToString()} is forbidden");
}
那东西对我来说很好用(感谢@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();
}
}