我的问题是:
如何使用C#禁用在文本框控件中按住键? 例如Boxxxxxxxxxxxxxxxxxxxxx
我不想让用户从键盘上重复任何字符。
有什么建议吗?
感谢
答案 0 :(得分:5)
每个人使用KeyDown和KeyUp事件抑制键重复只是一个额外的注释。如果你这样做,你需要排除捕获元键,如Alt / Shift等,否则当按下那些键时,你想要的实际键将不会被发送,因为这是一个两个组合键,KeyDown和KeyUp事件捕获所有键。
这适用于所有双键组合。 我没有将所有元键添加到以下示例中,只是最常见的。 您可以通过将自己的密钥添加到集合中来轻松添加自己的密钥。 从BFree的帖子扩展:
public partial class Form1 : Form
{
private static readonly System.Collections.Generic.ICollection<System.Windows.Forms.Keys) ExcludeKeys = new System.Collections.Generic.HashSet<System.Windows.Forms.Keys)()
{
System.Windows.Forms.Keys.None,
System.Windows.Forms.Keys.Shift,
System.Windows.Forms.Keys.ShiftKey,
System.Windows.Forms.Keys.LShiftKey,
System.Windows.Forms.Keys.RShiftKey,
System.Windows.Forms.Keys.Alt,
System.Windows.Forms.Keys.Control,
System.Windows.Forms.Keys.ControlKey,
System.Windows.Forms.Keys.LControlKey,
System.Windows.Forms.Keys.RControlKey,
System.Windows.Forms.Keys.CapsLock,
System.Windows.Forms.Keys.NumLock,
System.Windows.Forms.Keys.LWin,
System.Windows.Forms.Keys.RWin
}
private bool isKeyPressed = false;
public Form1()
{
InitializeComponent();
this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
}
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!ExcludeKeys.Contains(e.KeyCode))
{
isKeyPressed = false;
}
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (!ExcludeKeys.Contains(e.KeyCode))
{
e.SuppressKeyPress = isKeyPressed;
isKeyPressed = true;
}
}
}
答案 1 :(得分:4)
您可以在KeyEventArgs上使用SupressKeyPress属性:
public partial class Form1 : Form
{
private bool isKeyPressed = false;
public Form1()
{
InitializeComponent();
this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
}
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
isKeyPressed = false;
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = isKeyPressed;
isKeyPressed = true;
}
}
答案 2 :(得分:1)
我不熟悉c#中的细节,但我想象的是:
while (keyIsDown){
//do nothing
}
会奏效。如果没有办法跟踪按下的按键,我会感到惊讶。
答案 3 :(得分:1)
bool prevent = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = prevent;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
prevent = false;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
prevent = true;
}