我的问题是:
如何使用C#禁用在文本框控件中按住键?例如Boxxxxxxxxxxxxxxxxxxxxx
我不想让用户从键盘上重复任何字符.
有什么建议吗?
谢谢
您可以在 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;
}
}
Run Code Online (Sandbox Code Playgroud)
只是为每个人使用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;
}
}
}
Run Code Online (Sandbox Code Playgroud)